我有两个相关的组合框,combobox1填充了combobox2的项目。在combobox1 selectIndexChanged
事件中,我有这段代码,但我有错误Unknown column 'System.Data.DataRowView' in 'where clause'
。
我尝试在第一次选择时将此代码放入SelectionChangeCommitted
,它会填充正确的项目,但我的第二次选择我在comboBox2.Items.Clear();
州Items collection cannot be modified when the DataSource property is set.
中出错:(怎么办) ?
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string sql;
if (comboBox1.SelectedIndex >= 0)
{
comboBox2.Items.Clear();
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
sql = "SELECT brgyname,idbrgy from barangay where idmun=" + comboBox1.SelectedValue;
adapter.SelectCommand = new MySqlCommand(sql, conn);
DataTable cbBrgy = new DataTable();
adapter.Fill(cbBrgy);
comboBox2.DataSource = cbBrgy;
comboBox2.DisplayMember = "brgyname";
comboBox2.ValueMember = "idbrgy";
}
}
以下是我如何填充combobox1
private void cbMun()
{
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand("SELECT munname,idmun from municipality", conn);
DataTable cbMun = new DataTable();
adapter.Fill(cbMun);
comboBox1.DataSource = cbMun;
comboBox1.DisplayMember = "munname";
comboBox1.ValueMember = "idmun";
}
答案 0 :(得分:1)
当cbMun函数填充组合框时,它将直接调用组合框选择的索引更改事件,因此要解决此定义bool值comboisloading = true并修改您的代码,如下所示:
private void cbMun()
{
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
adapter.SelectCommand = new MySqlCommand("SELECT munname,idmun from municipality", conn);
DataTable cbMun = new DataTable();
adapter.Fill(cbMun);
comboBox1.DataSource = cbMun;
comboBox1.DisplayMember = "munname";
comboBox1.ValueMember = "idmun";
comboisloading = false;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboisloading)
return;
string sql;
if (comboBox1.SelectedIndex >= 0)
{
comboBox2.Items.Clear();
MySqlConnection conn = new MySqlConnection(sqlString);
MySqlDataAdapter adapter = new MySqlDataAdapter();
sql = "SELECT brgyname,idbrgy from barangay where idmun=" + comboBox1.SelectedValue;
adapter.SelectCommand = new MySqlCommand(sql, conn);
DataTable cbBrgy = new DataTable();
adapter.Fill(cbBrgy);
comboBox2.DataSource = cbBrgy;
comboBox2.DisplayMember = "brgyname";
comboBox2.ValueMember = "idbrgy";
}
}
答案 1 :(得分:0)
我只是将我的代码放在comboBox1_SelectionChangeCommitted
而不是comboBox1_SelectedIndexChanged
事件中,因为除非用户将更改提交给项目,否则仍然不生成comboBox1.SelectedValue
。同样来自Items collection cannot be modified when the DataSource property is set
的{{1}}错误我刚刚删除了这行代码。我仍然清理并正确更换我的combobox2物品。嗯..因为我曾经在vb中清除组合框。我想知道。
comboBox2.Items.Clear();