简体   繁体   中英

datagridview textbox control autocomplete - handle item not in list

I have this code to set one of my textbox columns in a datagridview to autocomplete:

private void datagridWorkorderPartItems_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        if (this.datagridWorkorderPartItems.CurrentCell.ColumnIndex == 2)
        {
            e.Control.KeyPress += Control_KeyPress;
            //  e.Control.KeyDown += Control_KeyDown;
        }
        else if (this.datagridWorkorderPartItems.CurrentCell.ColumnIndex == 4)
        {
            e.Control.KeyPress += Control_PriceKeypress;
        }
        else
        {

        }

        //make the part number column in the data grid view auto complete, and if the part is not in the list, need to add
        TextBox textPart = e.Control as TextBox;
        if (this.datagridWorkorderPartItems.CurrentCell.ColumnIndex == 3 && textPart != null)
            {
            textPart.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            textPart.AutoCompleteSource = AutoCompleteSource.CustomSource;
            Parts part = new Parts();
            DataTable partdata = new DataTable();
            partdata = part.LoadPartTable();
            foreach (DataRow row in partdata.Rows)
                {
                textPart.AutoCompleteCustomSource.Add(row["PartNumber"].ToString());
                }
            }
        else if (this.datagridWorkorderPartItems.CurrentCell.ColumnIndex != 3 && textPart != null)
            {
            textPart.AutoCompleteMode = AutoCompleteMode.None;
            }
    }

It works great but now I would like to handle an item that is typed in that does not match any item in the underlying list. It would allow free text entry but ask the user if they want to save the new item.

How can I do this?

See the answer of this SO question.

I would not recommend to ask user whether to save the new item into the AutoCompleteCustomSource . Rather it should be transparent to the user. I assume that you are updating the AutoCompleteCustomSource every time the editing control is attached with the data from part.LoadPartTable . If the PartTable is updated with the user entered data then next time when you set the AutoCompleteCustomSource from PartTable , the user entered data will be automatically added to AutoCompleteCustomSource .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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