2016-09-26 85 views
0

我有一個類foo。它用於顯示具有兩個可編輯參數的各種數據。我使用List來存儲我的程序必須管理的許多Foos。我在DataGridView對象中顯示我的foos。問題是,當我執行myRefresh()時,DataGridView對象中的適當項目未被選中。它不顯示選定行的數據,而是顯示行0的數據。任何想法可能會導致這種情況?以編程方式更改時不會發生SelectionChanged事件

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

您是否檢查過「int index = myTable.CurrentCell.RowIndex'是否返回了您期望的值。 – ChrisF

+0

@ChrisF是的,如果我選擇第七行,myTable.CurrentCell.RowIndex返回6. – Dan

+0

什麼是myList? – Hassan

回答

1

按照文檔

當你改變這個屬性的值,SelectionChanged事件 的CurrentCellChanged事件之前發生。在此時訪問CurrentCell屬性的任何SelectionChanged事件 將獲得其先前值 。

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

改變CurrentCell時,在你的代碼

所以,的SelectionChanged首先呼籲CurrentCellChanged的舊值。因此,請嘗試使用CurrentCellChanged事件來獲取CurrentCell的最新值。

相關問題