【问题标题】:how to allow user manual entry in datagridview combobox in c#如何允许用户在 c# 中的 datagridview 组合框中手动输入
【发布时间】:2011-02-11 11:04:27
【问题描述】:

我正在尝试在 datagridview 组合框中输入值。但它不允许。怎么办?

【问题讨论】:

    标签: c# datagridview


    【解决方案1】:
    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;
    
            }
    
        }
    

    【讨论】:

    • cbo_validating() 被连续调用,即使我将 e.cancel 设置为 true。有什么具体原因吗?
    【解决方案2】:

    也许,这个例子可读性更好:

    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;
            }
        }
    

    【讨论】:

      【解决方案3】:

      确保DataGridViewEditMode 属性设置为EditOnKeystrokeOrF2

      另外,验证ReadOnly 属性是否设置为False

      【讨论】:

      • 它不允许组合框
      • 什么不允许组合框?我刚刚尝试了一个带有这些属性的网格视图和一个列中的组合框。
      • 此选项对 datagridview 不起作用。根据您的回答,它只允许从组合框中选择值,不允许输入文本
      猜你喜欢
      • 2011-07-30
      • 1970-01-01
      • 2011-11-08
      • 1970-01-01
      • 2019-01-20
      • 2020-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多