2011-02-11 80 views

回答

8
private void GridStockItemEntry_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
    { 

     DataGridViewRow row = GridStockItemEntry.CurrentRow; 
     DataGridViewCell cell = GridStockItemEntry.CurrentCell; 
     if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl)) 
     { 

      if (cell == row.Cells["ItemName"] && Convert.ToString(row.Cells["Type"].Value) == "Raw Material") 
      { 
       DataGridViewComboBoxEditingControl cbo = e.Control as DataGridViewComboBoxEditingControl; 

       cbo.DropDownStyle = ComboBoxStyle.DropDown; 

       cbo.Validating += new CancelEventHandler(cbo_Validating); 
      } 
     } 


    } 
    void cbo_Validating(object sender, CancelEventArgs e) 
    { 

     DataGridViewComboBoxEditingControl cbo = sender as DataGridViewComboBoxEditingControl; 

     DataGridView grid = cbo.EditingControlDataGridView; 

     object value = cbo.Text; 

     // Add value to list if not there 

     if (cbo.Items.IndexOf(value) == -1) 
     { 

      DataGridViewComboBoxCell cboCol = (DataGridViewComboBoxCell)grid.CurrentCell; 

      // Must add to both the current combobox as well as the template, to avoid duplicate entries... 

      cbo.Items.Add(value); 

      cboCol.Items.Add(value); 

      grid.CurrentCell.Value = value; 

     } 

    } 
-1

確保DataGridViewEditMode屬性設置爲EditOnKeystrokeOrF2

同時,驗證ReadOnly屬性設置爲False

+0

它亙古不變的允許組合框 – Even 2011-02-11 11:29:38

+0

什麼不允許的組合框?我只是嘗試了一個帶有這些屬性的gridview和一列中的組合框。 – tzup 2011-02-11 13:15:57

1

也許,這個例子是更好的可讀性:

private void datagridview_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { 
     DataGridView dgv = (DataGridView)sender; 
     if(dgv.CurrentCell.ColumnIndex==dgv.Columns["ColumnName"].Index) { 
      ComboBox cbx = (ComboBox)e.Control; 
      cbx.DropDownStyle = ComboBoxStyle.DropDown; 
      cbx.AutoCompleteSource = AutoCompleteSource.ListItems; 
      cbx.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest; 
     } 
    } 
相關問題