input a multi digit number into a textbox and get a solution automatically without using a button

Viewed 31

I have been trying to create an automatic solution for my project where in when I input a number the corresponding data is displayed in a read-only textBox. This idea works great with a button as the input is a multi digit, the moment I input the first number the code calls the else function.

sample dB

b_id                 b_name
1                     Huston
15                    Berlin
06                    Rio

here when i enter the first b_id the output is Huston. the second one automatically calls Huston and third before i can enter the 2nd digit the code yells the else statement.

 private void textBox1_TextChanged(object sender, EventArgs e)
    {
        .........c#....

        SqlDataReader reader;
        con.Open();
        SqlCommand cmd = new SqlCommand("Select b_id,b_name from branches where b_id=@b_id", con);
        cmd.Parameters.AddWithValue("b_id", textBox1.Text);

        
        reader = cmd.ExecuteReader();
        try
        {
            if(reader.Read())
            {
                label2.Text = reader["b_name"].ToString();

            }
            else
            {
                MessageBox.Show("No data was found in this ID");

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }
1 Answers

You can re-write your if-else like below :

if(reader.Read())
    label2.Text = reader["b_name"].ToString();
else
    label2.Text = "No data found!";

Hitting the database each time you type a char in the textbox is not a good idea. A better approach could be what @Oliver suggested or if the table branches is not so big, load all the data into a datatable and search in it from your textchange event.

Related