BindingSource和DataGridView默认的当前位置

本文关键字:位置 默认 DataGridView BindingSource | 更新日期: 2023-09-27 17:52:34

BindingSource是否有一个自动默认的当前位置?我在CurrentCellChanged事件上有一个事件处理程序,它似乎被触发了两次。我正在使用BindingSource查找方法以编程方式设置起始位置,但在我设置起始位置之前,CurrentCellChanged已经启动,初始选择的单元格是第0列第0行。当你创建一个BindingSource时,它是否已经设置了Current属性?

BindingSource和DataGridView默认的当前位置

MSDN for DataGridView。CurrentCell属性提到默认的CurrentCell属性值是第一行中的第一个单元格(如果DGV中没有单元格,则为空)。

设置这个默认值将触发你的CurrentCellChanged事件,解释为什么你会看到单元格0,0的事件

我很确定你所看到的是DataGridView在数据绑定过程中触发其各种选择事件(CurrentCellChanged, SelectionChanged等)。因为您已将事件处理程序附加到它触发的其中一个事件。

解决这个问题的方法是附加一个事件处理程序到DataGridView的DataBindingComplete和附加你的CurrentCellChanged处理程序在那里。

// Attach the event in the form's constructor
this.dataGridView1.DataBindingComplete += new DataGridViewBindingCompleteEventHandler(dataGridView1_DataBindingComplete);
// And in the eventhandler, attach to the CurrentCellChanged event.
void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    dataGridView1.CurrentCellChanged += new EventHandler(dataGridView1_CurrentCellChanged);
}