如何在c#中的datagridview组合框中允许用户手动输入

时间:2011-02-11 11:04:28

标签: c# datagridview

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

3 个答案:

答案 0 :(得分: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 :(得分:4)

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

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

答案 2 :(得分:-2)

确保EditMode的{​​{1}}属性设置为DataGridView

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