2009-06-22 81 views
9

我在處理DataGridView中的選擇時遇到問題。 我的網格視圖包含一個金額列。表單上有一個文本框,用於顯示所選網格視圖行的總量。因此,當用戶選擇/取消選擇gridview行並相應地計算(增加/減少)數量時,我需要捕獲事件。我發現這樣做的方法有兩種:DataGridView捕獲用戶行選擇

  1. 使用RowEnterRowLeave事件。 當用戶選擇/取消選擇單行時,這些工作正常。但是,當用戶一次選擇多行時,只會觸發最後一行的事件。因此,從我的總金額只有最後一行的金額被加/減。從而使我的結果錯誤。

  2. 使用RowStateChanged事件。 這適用於多行。但是,如果用戶滾動瀏覽數據網格,事件將被觸發。

有沒有人處理過這種情況。我想知道我應該使用哪個datagrid事件,以便我的代碼只在用戶選擇/取消選擇包括多行的行時執行。

回答

15

找到解決方案。我可以使用RowStateChanged和運行我的代碼只有StateChanged該行是Selected ...

private void dgridv_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e) 
{ 
    // For any other operation except, StateChanged, do nothing 
    if (e.StateChanged != DataGridViewElementStates.Selected) return; 

    // Calculate amount code goes here 
} 
0

您可以使用您的第一個方法(行輸入行離開)以及SelectedRows屬性。這意味着,當您檢測到這些事件時,您需要計算,而不是使用事件參數中的行,循環訪問SelectedRows並獲取總計。

+0

我不能這樣做,因爲我需要從最初選擇的,而不是現在選擇那些記錄減額。 – 2009-06-22 14:11:15

2

你可以簡單地捕捉這在下面的方式,但它僅限於單一行選擇:

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) 
{ 
    MessageBox.Show("Selected row is=" + e.RowIndex); 
    // you can perform (any operation) delete action on selected row like 

    dataGridView1.Rows.RemoveAt(e.RowIndex); 
    dataGridView1.Refresh(); 
} 
+1

用戶用鍵盤輸入一行時不夠用 – Alireza 2013-11-12 11:42:04

2

我覺得你可以考慮SelectionChanged事件:

private void DataGridView1_SelectionChanged(object sender, EventArgs e) { 
    textbox1.Text = DataGridView1.SelectedRows.Count.ToString(); 
} 
2

我用的SelectionChanged甚至T或CellValueChanged事件:

 dtGrid.SelectionChanged += DataGridView_SelectionChanged; 
     this.dtGrid.DataSource = GetListOfEntities; 
     dtGrid.CellValueChanged += DataGridView_CellValueChanged; 


    private void DataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e) 
    { 
     DataGridViewRow row = dtGrid.Rows[e.RowIndex]; 
     SetRowProperties(row); 
    } 

    private void DataGridView_SelectionChanged(object sender, EventArgs e) 
    { 
     var rowsCount = dtGrid.SelectedRows.Count; 
     if (rowsCount == 0 || rowsCount > 1) return; 

     var row = dtGrid.SelectedRows[0]; 
     if (row == null) return; 
     ResolveActionsForRow(row); 
    } 
+0

什麼是SetRowProperties? – John 2016-11-15 19:59:40