简体   繁体   English

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

[英]how to allow user manual entry in datagridview combobox in c#

I am trying to enter values in a datagridview Combobox. 我想在datagridview Combobox中输入值。 but it does not Allows. 但它不允许。 What to do? 该怎么办?

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;

        }

    }

Maybe, this example is better readable: 也许,这个例子更具可读性:

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

Make sure that EditMode property of the DataGridView is set to EditOnKeystrokeOrF2 确保DataGridView EditMode属性设置为EditOnKeystrokeOrF2

Also, verify that ReadOnly property is set to False . 另外,验证ReadOnly属性是否设置为False

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM