不知道大家有没有遇到过这个问题,在winform开发软件的过程中,使用Datagridview代码设置选中行后,没有触发SelectionChanged事件,但是通过界面点击单元格或者选中行却是可以触发SelectionChanged事件的。
可能平时只设置this.dataGridView.Rows[index].Selected = true这行代码就可以满足要求了,界面上看确实是选中了的,但是如果除了上面提到的只设置这行代码是不能触发SelectionChanged事件的,那就不能满足你这个事件中的代码块功能的执行。除此之外还有一个问题,比如你在写行移动时,上下移动时需要在代码中设置选中行的,如果也只是用这一行代码设置选中行,你会发现界面上看到的行选中了,但是实际并没有选中,这就会影响你对当前行数据的正确获取,从而影响上下移动功能的效果。
所以,针对这两种情况带来的困扰,有两种方式解决方案:
1)在你设置选中行的代码块处,完成SelectionChanged的内容
2)(推荐)在设置选中行代码前,设置dataGridView.CurrentCell = null,就能触发SelectionChanged事件,详见下面代码
下见代码:
private void DataGridView1_SelectionChanged(object sender, EventArgs e)
{
var curRow = this.dataGridView1.CurrentRow;
if (curRow == null)
return;
if (curRow.Cells[0].Value == null)
return;
var action = this.actions.Find(p => p.ActionName == curRow.Cells[0].Value.ToString());
this.tb_describle.Text = action.ChiDescrible;
}
//设置选中行
if (this.dataGridView1.RowCount > 0)
{
this.dataGridView1.CurrentCell = null;
this.dataGridView1.Rows[0].Selected = true;
this.dataGridView1.CurrentCell = this.dataGridView1.Rows[0].Cells[0];
}