以编程方式更改时不发生SelectionChanged事件
本文关键字:SelectionChanged 事件 编程 方式更 | 更新日期: 2023-09-27 18:08:46
我有一个类foo。它用于显示带有两个可编辑参数的各种数据。我使用List来存储我的程序必须管理的许多foo。我在DataGridView对象中显示我的foos。问题是,当我执行myRefresh()时,没有选择DataGridView对象中的适当项。它不显示所选行的数据,而是显示第0行的数据。知道是什么引起的吗?
List<foo> myFoos = new List<foo>(); //List is populated elsewhere in code.
public class foo
{
public string p1 { get; set; }
public string p1_prefix { get; set; }
public string p1_postfix { get; set; }
public string p2 { get; set; }
public string p2_prefix { get; set; }
public string p2_postfix { get; set; }
public override string ToString()
{
return (p1_prefix + " " + p1 + " " + p1_postfix + " " + p2_prefix + " " + p2 + " " + p2_postfix);
}
}
private void myTable_SelectionChanged(object sender, EventArgs e)
{
Pre1.Text = myList[myTable.CurrentCell.RowIndex].p1_prefix;
Edit1.Text = myList[myTable.CurrentCell.RowIndex].p1;
Post1.Text = myList[myTable.CurrentCell.RowIndex].p1_postfix;
Pre2.Text = myList[myTable.CurrentCell.RowIndex].p2_prefix;
Edit2.Text = myList[myTable.CurrentCell.RowIndex].p2;
Post2.Text = myList[myTable.CurrentCell.RowIndex].p2_postfix;
}
private void myRefresh()
{
int index = myTable.CurrentCell.Rowindex;
myDraw();
myTable.CurrentCell = myTable[0, index]; //There is only one column in myTable
}
private void myDraw()
{
myTable.Rows.Clear();
foreach(foo f in myFoos)
myTable.Rows.Add(new object[] { f.toString() };
}
按文档
当您更改此属性的值时,SelectionChanged事件发生在CurrentCellChanged事件之前。任何SelectionChanged事件此时访问CurrentCell属性的处理程序将获得它的前一个值。
https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.currentcell (v = vs.110) . aspx
所以在你的代码中,当改变CurrentCell时,selectionChanged首先在CurrentCellChanged的旧值上调用。因此,尝试使用CurrentCellChanged事件来获取CurrentCell的最新值。