2017-04-27 43 views
0

我有一個DataTable作爲DataSource一個DataGridView,在DataGridView一個Label顯示當前選擇的細胞處理和最後有該按鈕開口的MessageBox以顯示一個Button當前選擇的單元地址相同。DataGridView的與數據源報告兩個不同CurrentCellAddress行值

標籤的文字在DataGridViewsCellClick事件中更新。

以下圖爲例:選擇最後一個「NewRow」時,標籤將正確更新爲正確的第五行(5)索引。但是,當我點擊按鈕並顯示相同的選定單元格地址時,行索引爲四(4)。

我猜這與DataSource/DataTable有關,因爲如果DataGridView未綁定到數據源,則不會發生這種情況。

enter image description here

我有一種解決方法,但我不理解爲什麼dataGridView1.CurrentCellAddress似乎返回不正確/不同的值相同的方法。在單元格單擊事件中調用方法CurrentCellAddress時發生了什麼,並且稍後單擊該按鈕時會調用相同的方法?選擇沒有改變,但看起來它們是不同的數字。謝謝你的幫助。

代碼我用來測試這個...

DataTable gridData; 

public Form1() { 
    InitializeComponent(); 
} 

private void Form1_Load(object sender, EventArgs e) { 
    //FillGrid(); 
    gridData = GetTable(); 
    FillDT(gridData); 
    dataGridView1.DataSource = gridData; 
    label1.Text = "CurrentCellAddress: " + dataGridView1.CurrentCellAddress.ToString(); 
} 

private DataTable GetTable() { 
    DataTable dt = new DataTable(); 
    dt.Columns.Add("Col1", typeof(String)); 
    dt.Columns.Add("Col2", typeof(String)); 
    dt.Columns.Add("Col3", typeof(String)); 
    return dt; 
} 

private void FillDT(DataTable dt) { 
    for (int i = 0; i < 5; i++) { 
    dt.Rows.Add("R" + i + "C1", "R" + i + "C2", "R" + i + "C3"); 
    } 
} 

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { 
    label1.Text = "CurrentCellAddress: " + dataGridView1.CurrentCellAddress.ToString(); 
} 

private void btnGetCellAddress_Click(object sender, EventArgs e) { 
    MessageBox.Show("CurrentCellAddress: " + dataGridView1.CurrentCellAddress.ToString(),"Cell Address"); 
} 

// Method to fill the grid to show the values are correct 
// when the datagridview is not data bound 
private void FillGrid() { 
    dataGridView1.Columns.Add(new DataGridViewTextBoxColumn()); 
    dataGridView1.Columns.Add(new DataGridViewTextBoxColumn()); 
    dataGridView1.Columns.Add(new DataGridViewTextBoxColumn()); 
    for (int i = 0; i < 5; i++) { 
    dataGridView1.Rows.Add("R" + i + "C1", "R" + i + "C2", "R" + i + "C3"); 
    } 
} 

回答

1

DataGridView控制的丟失焦點OnValidating方法(source reference)最終被調用,它包含以下代碼:

// Current cell needs to be moved to the row just above the 'new row' if possible. 
int rowIndex = this.Rows.GetPreviousRow(this.ptCurrentCell.Y, DataGridViewElementStates.Visible); 

選擇DataGridView中的單元格會將注意力集中在控件上,因此不會調用它。但是,使用按鈕時焦點會丟失,並且OnValidating會將當前單元格移動到空白新行上方一行。

+1

你是對的。答案中的鏈接也解釋了爲什麼在沒有數據源的情況下值正確返回。在你鏈接到的'OnRowValidated'引用的大if語句中的第一個條件是if(this.DataSource!= null &&'... ..這看起來可以解釋發生了什麼。謝謝你提供深入的解釋。 – JohnG

相關問題