问题
I have a DatagridView with two DataGridViewComboBoxCell:
- Administration
- Employee.
What I want to do is when I select an administration from 1st
DataGridViewComboBoxCell, I'll get the list of the employees of selected
Admininstration in the 2nd DataGridViewComboBoxCell. I binded the first
DataGridViewComboBoxCell manually to administrationBindingSource and I tried
this answer code, This is the code I used:
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();
}
This code works fine in the first time but when I try to update admininstration value I got this error message:
DataGridViewComboBoxCell value is invalid
How to fix it?
回答1:
Try to clear the value of employee cell before rebind it in the void
"selectEmployee", something like:
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();
}
来源:https://stackoverflow.com/questions/28854881/datagridviewcomboboxcell-valuevalue-is-invalid-with-binded-datagridviewcomboboxc