Home > Mobile >  Search the combo box c#
Search the combo box c#

Time:03-04

I am building a library software and I need some help from you. In the book lending section, I have a text box for typing the book number and a combo for the book name. The system is such that when I type the book's id in the text box, it comes up with its name in the combo box, like searching in the data grid view. The problem is that I do not know how to code the database and call and in general it is better to say I do not know what to do! Please help.

CodePudding user response:

If you want the combobox to display the book name according to the Id you enter in the textbox, you can refer to the following code:

string connStr = " Your own database connect string ";
string sql = "select Name from Book where Id=@id";//Your own sql query statement
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        comboBox1.Items.Clear();
        SqlConnection conn = new SqlConnection(connStr);
        using (conn)
        {
            SqlParameter parm = new SqlParameter("@id", Convert.ToInt32(textBox1.Text));
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = sql;
            cmd.Connection = conn;
            cmd.Parameters.Add(parm);
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    comboBox1.Text = dr.GetValue(0).ToString();
                }
            }
            else
            {
                MessageBox.Show("Please enter correct ID");
            }
        }
    }
  • Related