我在我的程序中发现了一个有趣的现象,我的程序中有两个带checkbox的datagridview,他们有一定的关联性,我想选中datagridview1中某一行的checkbox,选中后datagridview2中的相应行checkbox也被选中。
private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 3)
{
if (dataGridView2.Rows[e.RowIndex].Cells[3].Value != null)
{
if (Convert.ToBoolean(dataGridView2.Rows[e.RowIndex].Cells[3].Value.ToString()) == true)
{ DataGridViewCheckBoxCell checkCell1 = (DataGridViewCheckBoxCell)dataGridView2.Rows[e.RowIndex].Cells["是否被选"];
checkCell1.Value = false;
DataGridViewCheckBoxCell checkCell2 = (DataGridViewCheckBoxCell)dataGridView5.Rows[e.RowIndex].Cells["是否被选"];
checkCell2.Value = false;
}
else
{
DataGridViewCheckBoxCell checkCell3 = (DataGridViewCheckBoxCell)dataGridView2.Rows[e.RowIndex].Cells["是否被选"];
checkCell3.Value = true;
DataGridViewCheckBoxCell checkCell4 = (DataGridViewCheckBoxCell)dataGridView5.Rows[e.RowIndex].Cells["是否被选"];
checkCell4.Value = true;
} }
else
{
this.dataGridView5["是否被选", e.RowIndex].Value = true;
}
}
}但是我每次操作第一次无效,从第二次开始才能有效,不知为什么! 即我第一次选中datagridview1中的某一行 datagridview2中相应行没有被选中,而从第二次开始才能被选中 哪位高手能告诉我这是为什么?
private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 3)
{
if (dataGridView2.Rows[e.RowIndex].Cells[3].Value != null)
{
if (Convert.ToBoolean(dataGridView2.Rows[e.RowIndex].Cells[3].Value.ToString()) == true)
{ DataGridViewCheckBoxCell checkCell1 = (DataGridViewCheckBoxCell)dataGridView2.Rows[e.RowIndex].Cells["是否被选"];
checkCell1.Value = false;
DataGridViewCheckBoxCell checkCell2 = (DataGridViewCheckBoxCell)dataGridView5.Rows[e.RowIndex].Cells["是否被选"];
checkCell2.Value = false;
}
else
{
DataGridViewCheckBoxCell checkCell3 = (DataGridViewCheckBoxCell)dataGridView2.Rows[e.RowIndex].Cells["是否被选"];
checkCell3.Value = true;
DataGridViewCheckBoxCell checkCell4 = (DataGridViewCheckBoxCell)dataGridView5.Rows[e.RowIndex].Cells["是否被选"];
checkCell4.Value = true;
} }
else
{
this.dataGridView5["是否被选", e.RowIndex].Value = true;
}
}
}但是我每次操作第一次无效,从第二次开始才能有效,不知为什么! 即我第一次选中datagridview1中的某一行 datagridview2中相应行没有被选中,而从第二次开始才能被选中 哪位高手能告诉我这是为什么?
datagridview2.EndEdit()
加在 if (dataGridView2.Rows[e.RowIndex].Cells[3].Value != null) 前面
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.BeginEdit();
dataGridView2.BeginEdit();
if (e.ColumnIndex == 0)
{
if (dataGridView1.Rows[e.RowIndex].Cells["Column1"].Value == "true")
{ DataGridViewCheckBoxCell checkCell1 = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells["Column1"];
checkCell1.Value = true;
DataGridViewCheckBoxCell checkCell2 = (DataGridViewCheckBoxCell)dataGridView2.Rows[e.RowIndex].Cells["Column2"];
checkCell2.Value = true; }
else
{
DataGridViewCheckBoxCell checkCell3 = (DataGridViewCheckBoxCell)dataGridView1.Rows[e.RowIndex].Cells["Column1"];
checkCell3.Value = false;
DataGridViewCheckBoxCell checkCell4 = (DataGridViewCheckBoxCell)dataGridView2.Rows[e.RowIndex].Cells["Column2"];
checkCell4.Value = false;
}
}
}