简体   繁体   中英

SelectionChanged event not occuring when changed programmatically

I have a class, foo. It is used to show various data with two editable parameters. I use a List to store the many foos my program will have to manage. I display my foos in a DataGridView object. The problem is that when I execute myRefresh(), the proper item in the DataGridView object is not selected. Instead of displaying the data for the selected row, it shows the data for Row 0. Any idea what may be causing this?

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() };
}

As per the documentation

When you change the value of this property, the SelectionChanged event occurs before the CurrentCellChanged event. Any SelectionChanged event handler accessing the CurrentCell property at this time will get its previous value.

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

So in your code when changing the CurrentCell, the selectionChanged is called first on the old value of the CurrentCellChanged. So try using the CurrentCellChanged event to get the latest value of the CurrentCell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM