C# Combobox and SQL

Asked

Viewed 150 times

0

I would like to know how to load values in a combobox, listing an entire column of the database, for example, I have a column called "Beer" and it has several names, I would like to list this column in a Combobox. Thanks.

I have a stored procedure:

CREATE PROCEDURE [dbo].[LoadCerveja]
(
    @Cerveja varchar(60)
)
AS
    SELECT @cerveja from Ingredientes
RETURN

and in the code I need to add to the formLoad for him to pull the "Beer" column from the database.

I tried to do the following (in the form load)

private void Form1_Load(object sender, EventArgs e)
{
try
{
conexao.Open();
SqlCommand cmdd = new SqlCommand("LoadIngredients", conexao);
cmdd.CommandType = CommandType.StoredProcedure;
cmdd.Parameters.Add("@Cerveja");
SqlDataReader DR;
DR = cmdd.ExecuteReader();
{
 comboBox1.Items.Add(DR.GetValue()); **// Não sei o que fazer aqui pra        adicionar      os dados ao combobox !!!!**
}
else MessageBox.Show("Erro ao buscar receita no DB.");

}

  • 1

    Could you add more information to the question? It will look better to help you if you have more information. Have some code where you try to load the information in the combobox?

  • I’ve edited here, thanks

1 answer

2


There is an example in the documentation on the Sqldatareader..

....
    SqlDataReader DR = cmdd.ExecuteReader();

    if (DR.HasRows)
    {
      while (DR.Read())
      {
          comboBox1.Items.Add(DR.GetString(0)); 
      }
    }
    else
    {
      Console.WriteLine("No rows found.");
    }
    DR.Close();
....

In your Parameters you can insert the value in two ways

cmdd.Parameters.Add("@Cerveja", SqlDbType.VarChar).Value = "valor"

or

cmdd.Parameters.AddWithValue("@Cerveja", valor);

I hope I’ve helped!

  • Thanks for the support milestones Giovanni! I have a problem with the cmdd.Parameters.Add("@Beer"); The parameter is wrong and I don’t know how to fix it, it needs a value object...

  • I edited the answer..

  • I did without using stored Procedure, I created a string with the select instruction and it worked, thanks my brother was exactly that

  • Beauty!! Then mark as the right answer, on V, just below the points arrows of the answer ^^

Browser other questions tagged

You are not signed in. Login or sign up in order to post.