在以编程方式更改时未发生SelectionChanged事件

时间:2016-09-26 12:03:11

标签: c# datagridview

我有一个班,foo。它用于显示具有两个可编辑参数的各种数据。我使用List来存储我的程序必须管理的许多foos。我在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() };
}

1 个答案:

答案 0 :(得分:1)

根据文件

  

更改此属性的值时,SelectionChanged事件   发生在CurrentCellChanged事件之前。任何SelectionChanged事件   此时访问CurrentCell属性的处理程序将获得它   以前的价值。

https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.currentcell(v=vs.110).aspx

因此,在更改CurrentCell的代码中,首先在CurrentCellChanged的旧值上调用selectionChanged。因此,请尝试使用CurrentCellChanged事件来获取CurrentCell的最新值。

相关问题