Combobox and Sqlreader

Asked

Viewed 34 times

0

I have a ComboBox with a list of items containing names that are generated from my database (I pull up the name of coluna beer that are allocated in the table):

private void Form1_Load(object sender, EventArgs e)
{
   try
   {
   conexao.Open();
   SqlCommand cmdd = new SqlCommand("select Cerveja from Cervejas where Cerveja ='" + comboBox1.SelectedItem + "'", conexao);
   SqlDataReader DR;
   DR = cmdd.ExecuteReader();
   if (DR.HasRows)
   {
     while (DR.Read())
     {
        comboBox1.Items.Add(DR.GetString(0));
     }
   }
   else
   {
        MessageBox.Show("Não tem cervejas no nosso banco de dados!");
   }

From this code I can get the name of the "Beers" column on the combobox when starting the program. What I need to do now, is when the user selects an item in the combobox, it makes a comparison with the name of the combobox item and the beers in the database, pulling the right beer Row, I was trying so but I can’t:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
        try
        {
            conexao.Open();
            SqlCommand cmd = new SqlCommand("select * from Cervejas where Cerveja ='" + comboBox1.SelectedItem + "'", conexao);
            SqlDataReader DR;
            DR = cmd.ExecuteReader();
            if (DR.Read())
            {
                if (comboBox1.SelectedItem == DR.GetValue(1))
                {
                    MessageBox.Show("teste");
                }
                else MessageBox.Show("teste2");
            }
        }
        catch (Exception ex)
        {
            conexao.Close();
            MessageBox.Show("Erro de conexão Modbus: \n\n" + ex.Message);
        }

In this case, in this part:

if (comboBox1.SelectedItem == DR.GetValue(1))
{
   MessageBox.Show("teste");
}

I make this comparison, if the selected item matches some beer in the database should print the word 'test', but this does not happen.

1 answer

0

The verification with the if era unnecessary, once I use the clause WHERE in the cmd.

I just edited:

SqlDataReader DR;
DR = cmd.ExecuteReader();
if (DR.Read())
{
     Messagebox.Show = DR.GetValue(0).ToString(); // teste
}

Browser other questions tagged

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