Prakash Mondal

Prakash Mondal

  • NA
  • 288
  • 209k

how to set selected value from database in combobox c#

Apr 24 2021 11:30 AM
private void Form1_Load(object sender, EventArgs e)
        {
cn.con.Open();
            DataTable dt = new DataTable();
            string sql = "SELECT * FROM STUDENTMAS";
            SqlDataAdapter da = new SqlDataAdapter(sql, cn.con);

            da.Fill(dt);
            dataGridView2.AutoGenerateColumns = false;
            dataGridView2.DataSource = dt;
            cn.con.Close();
        }
 
 
 
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
// load category comboBox2 =================================================
 
DB_CONNECTION cn = new DB_CONNECTION();
            cn.con.Open();
            cn.cmd.Connection = cn.con;
            cn.cmd.CommandText = "SELECT ID,NAME FROM CATEGORYTB ";
            System.Data.SqlClient.SqlDataReader dr;
            dr = cn.cmd.ExecuteReader();
            if (dr.HasRows)
            {
                combobox_id.Items.Clear();
                while (dr.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dr["NAME"].ToString();
                    item.Value = dr["ID"].ToString();
                    comboBox2.Items.Add(item);
                }
            }
            cn.con.Close();
 
//===================================================================
 
 // How to load category comboBox2 with a value of category field in studentmas table.
 
 // I try several processes, but not load
 
//comboBox1.SelectedIndex = comboBox1.FindStringExact(dataGridView2.Rows[e.RowIndex].Cells["ID"].Value.ToString());
 //comboBox1.SelectedValue = dataGridView2.Rows[e.RowIndex].Cells["ID"].Value.ToString();
 //comboBox1.SelectedIndex = comboBox1.Items.IndexOf(dataGridView2.Rows[e.RowIndex].Cells["ID"].Value.ToString());
}
 
 
Database table (categoryTB):
 id name status_flag
 C1 General Y
 C2 SC Y
 C3 ST Y
 C4 OBC Y
 
DatabaseTable(studentmas) :
 roll_no name session semester category
 R1 Rahit Autumn 2021 C1
 R2 Rahon Spring 2021 C1
 R3 Smith Spring 2021 C3
 R5 Alam Autumn 2021 C2
 
 
 
 Please help
 

Answers (1)