Wednesday, September 13, 2017

c# windows application combo box search

First open visual studio File->New->Project->Windows Forms Application-> Ok












Then we use toolbox for design the combo box and data tables.











Click on the combo box and paste the code.

  public Form1()
        {
            InitializeComponent();
            combo();
          
        }
        SqlConnection con = new SqlConnection(@"Data Source=USER;Initial Catalog=testo;Integrated Security=True");
    

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select * from yy  where id ='" + comboBox2.Text + "'";

                cmd.ExecuteNonQuery();
                DataTable dt = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dt);
                dataGridView1.DataSource = dt;
                con.Close();
            
        
        }

This is a function which calls at the first for showing the drop-down menu.

           void combo (){
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select id from yy";

            cmd.ExecuteNonQuery();
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
           foreach (DataRow dr in dt.Rows)
           {
            comboBox2.Items.Add(dr["id"].ToString());
           }
            con.Close();
            }

    }
Now  we execute this code . Then search data by id in dropdown menu.












If you like my blog share it.

No comments:

Post a Comment