我正在制作Windows应用程序并且卡在一个地方。
我的问题是我希望通过选择DataGridView
项目在ComboBox
中显示记录,但我不明白正确的方法。请帮我解决这个问题。
private void grid_Load(object sender, EventArgs e)
{
con = new SqlConnection(constr);
try
{
con.Open();
//this.studTableAdapter.Fill(this.pRJTestDBDataSet.stud);
//above line show error for connection to database
da = new SqlDataAdapter("SELECT stud_no FROM stud", con);
DataTable dt = new DataTable();
da.Fill(dt);
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "stud_no";
comboBox1.ValueMember = "stud_no";
comboBox1.DataSource = dt;
comboBox1.SelectedIndex = -1;
comboBox1_SelectedIndexChanged(sender, e);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{ con.Close(); }
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
this.studTableAdapter.Fill(pRJTestDBDataSet.stud);
//above line show error for connection to database
}
我已经尝试了上面的代码,但它没有在那里工作错误,如登录失败的用户
答案 0 :(得分:2)
cmd = new SqlCommand("SELECT stud_no FROM stud", con);
da = new SqlDataAdapter(cmd);
da.Fill(dt);
Combobox1.DataSource = dt;
Combobox1.DisplayMember = dt.Columns("Stud_no").ToString;
答案 1 :(得分:0)
使用要绑定的数据在组合框的每个选定项目索引更改事件中绑定DataGrid。
答案 2 :(得分:-1)
private void button2_Click(object sender, EventArgs e)//button 2 is a show data button
{
if (combo_floor.Text != "")
{
DataSet ds = new DataSet();
string sql = "select floor_id,floor_no,floor_remark,floor_entrydate from Floorinfo where floor_no='"+combo_floor.Text+"'";
ds = c.select_query(sql);
dataGridView1.DataSource = ds.Tables["a"];
combo_floor.Text = "";
}
else
{
showdata();
//showdata()is made for show all data from the given table name
}
}
//连接处于不同的类别,所以请不要介意