我有一个带有两个DataGridViewComboBoxCell:的DatagridView
- 管理
- 员工
我想做的是当我从第一个中选择一个管理
DataGridViewComboBoxCell,我将获得所选的员工列表
第二个DataGridViewComboBoxCell中的管理。我绑定了第一个
DataGridViewComboBoxCell手动管理BindingSource,我尝试了
这个答案代码,这是我使用的代码:
dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(dataGridView1_CellValueChanged);
dataGridView1.CurrentCellDirtyStateChanged += new EventHandler(dataGridView1_CurrentCellDirtyStateChanged);
void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
{
// This fires the cell value changed handler below
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex == -1)
{
return;
}
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.CurrentRow.Cells["administrationColumn"];
int item = 0;
if (cb.Value != null)
{
item = (Int32)cb.Value;
selectEmployee(item);
dataGridView1.Invalidate();
}
}
private void selectEmployee(int idAdministration)
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
SqlCommand Cmd = new SqlCommand("SELECT * FROM Employee WHERE IdAdministration = @idAdministration", con);
Cmd.Parameters.AddWithValue("@idAdministration", idAdministration);
DataTable Dt = new DataTable();
Dt.Load(Cmd.ExecuteReader());
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.CurrentRow.Cells["Employee"];
cb.DataSource = Dt;
cb.DisplayMember = "Name";
cb.ValueMember = "CodeEmployee";
con.Close();
}
这个代码第一次运行得很好,但当我尝试更新管理值时,我收到了以下错误消息:
DataGridViewComboBoxCell值是无效的
如何修复?
在将employee单元格重新绑定到void 之前,请尝试清除该单元格的值
"selectEmployee",类似于:
private void selectEmployee(int idAdministration)
{
if (con.State != ConnectionState.Open)
{
con.Open();
}
SqlCommand Cmd = new SqlCommand("SELECT * FROM Employee WHERE IdAdministration = @idAdministration", con);
Cmd.Parameters.AddWithValue("@idAdministration", idAdministration);
DataTable Dt = new DataTable();
Dt.Load(Cmd.ExecuteReader());
DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.CurrentRow.Cells["Employee"];
cb.Value = null; //add this
cb.DataSource = Dt;
cb.DisplayMember = "Name";
cb.ValueMember = "CodeEmployee";
con.Close();
}