2011-01-19 127 views

回答

6

我解決了它這樣做:

myDataGridView.EditingControlShowing += new System.Windows.Forms.DataGridViewEditingControlShowingEventHandler(myDataGridView_EditingControlShowing); 

    private void myDataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
    { 
     if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl)) 
     { 
      ComboBox cmb = (ComboBox)e.Control; 
      cmb.SelectionChangeCommitted -= new EventHandler(cmb_SelectionChangeCommitted); 
      cmb.SelectionChangeCommitted += new EventHandler(cmb_SelectionChangeCommitted); 
     } 
    } 

    void cmb_SelectionChangeCommitted(object sender, EventArgs e) 
    { 
     dgvPresupuesto.CurrentCell.Value = ((DataGridViewComboBoxEditingControl)sender).EditingControlFormattedValue; 
    } 
0

組合框的值的變化實際上是與網格關聯的編輯控件。 因此,要啓動什麼,你將不得不添加這些在DataGrid的EditingControlShowing事件爲特定列

private void dg_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
{ 
    if (dg.CurrentCell.ColumnIndex == 0) 
    { 
    ComboBox cmbox = e.Control as ComboBox; 
    cmbox.SelectedValueChanged += new EventHandler(cmbox_SelectedValueChanged); 
    } 
} 

你可以調用在下拉列表中選擇cvalue改變事件的單元格的值更改事件

+0

這方法不起作用,因爲該值尚未提交給底層DataGridViewCell.Value和DataGridView.CellValueChanged的EventHandler,我無法確定新值是什麼。我需要找到一種方法來強制datagrid本身將更改提交給單元格並引發`CellValueChanged`事件。 – bitbonk 2011-01-20 08:51:41

+0

在這種情況下,您可以使用SendKeys.Send(「{TAB}」)觸發TAB事件;在組合框事件處理程序中強制單元失去焦點,最終觸發網格的CellValueChanged – V4Vendetta 2011-01-20 10:32:08

+0

這也不理想,因爲當前單元格將失去焦點。這不應該發生在我的情況。 – bitbonk 2011-01-20 13:02:16

2

我最終這樣做了。我不知道如果是這樣的「首選」的方式或是否會產生任何副作用以後,但現在它似乎工作:

this.gridView.EditingControlShowing += this.GridViewOnEditingControlShowing; 

private void GridViewOnEditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
{ 
    ComboBox cellComboBox = e.Control as ComboBox; 
    if (cellComboBox != null) 
    { 
     // make sure the handler doen't get registered twice 
     cellComboBox.SelectionChangeCommitted -= this.CellComboBoxOnelectionChangeCommitted; 
     cellComboBox.SelectionChangeCommitted += this.CellComboBoxOnelectionChangeCommitted; 
    } 
} 

private void CellComboBoxOnelectionChangeCommitted(object sender, EventArgs e) 
{ 
    DataGridViewComboBoxEditingControl comboBox = sender as DataGridViewComboBoxEditingControl; 
    if (sender == null) 
    { 
     return; 
    }  
    if (comboBox.SelectedValue == null) 
    { 
     return; 
    }  
    if (this.gridView.CurrentCell.Value == comboBox.SelectedValue) 
    { 
     return; 
    }  
    this.gridView.CurrentCell.Value = comboBox.SelectedValue;   
} 
相關問題