Search code examples
c#sqlsql-servervisual-studioexecutereader

SQL Server Column to Combobox?


I have a table called Product. One of the columns of this table is called Naam. It's the name of the product. When you press on the button, all product names have to be added to the combobox.

So if I have 2 products: Cola & Fanta.

The program has to show only the column Naam in the combobox. Not the other columns.

I have already this for my button, but it doesn't work.

db.AlleProducten("Select Naam from Product;", Product);
cb_product.Items.Add(Product.Naam);

And this is the method that runs the query:

public void AlleProducten(string commandText, product Product)
{
    using (SqlConnection conn = new SqlConnection(connectionString))
    using (SqlCommand cmd = new SqlCommand(commandText, conn))
    {
        conn.Open();

        using (var rdr = cmd.ExecuteReader())
        {
             if (rdr.HasRows)
             {
                 rdr.Read();
                 Product.Naam = rdr.GetString(1);
                 conn.Close();
             }
        }
    }
}

The error:

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll

Additional information: De index ligt buiten de matrixgrenzen.

The additional information is in Dutch. Translated to English:

The index is located outside of the array bounds.


Solution

  • 1 - You are out of range due you are using rdr.GetString(1) instead of rdr.GetString(0)

    2 - There isn't any ComboBox in your code.

    using (var rdr = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            Product.Naam = rdr.GetString(0);
            YourComboBox.Items.Add(Product.Naam); 
        }
    }
    

    Take a look at SqlCommand.ExecuteReader documentation.