简体   繁体   中英

DataGridView ComboBox column not accepting new values

I have a DataGridView control in my Windows Forms application that allows users to edit product listing. To edit the product category, I want user to add new entries or select from the ones already entered before. To achieve this I added a comboBox column that is binded to a DataSource that gets the distinct category names from the products table. With the help of some other SO questions I was able make this comboBox editable using this code:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (dataGridView1.CurrentCell.ColumnIndex == CategorySelector.Index)
    {
        ComboBox combo = e.Control as ComboBox;
        if (combo == null)
            return;
        combo.DropDownStyle = ComboBoxStyle.DropDown;
    }
}

But the problem is that when I try to edit the category comboBox column and add new category other than the listed, and when I switch to other cell, it switches back to old category item for existing product or blank for new product. Please tell me how can I add new category through this comboBox column?

Finally I solved it by myself. I implemented the LostFocus event of the comboBox where I added the code for updating the bound DataSet with the new item.

The item is successfully added but one problem still persists. The item is not selected after it's added. ComboBox still resets to the previous selection. However, I can select the new item manually. But if you can solve this bug it will become a better UX for the user. Following is how I achieved new item adding:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (dataGridView1.CurrentCell.ColumnIndex == CategorySelector.Index)
    {
        ComboBox combo = e.Control as ComboBox;
        if (combo == null)
            return;
        combo.DropDownStyle = ComboBoxStyle.DropDown;
        combo.LostFocus += combo_LostFocus;
    }
}
void combo_LostFocus(object sender, EventArgs e)
{
    ComboBox c = (ComboBox)sender;
    if (c.FindStringExact(c.Text.Trim().ToLower()) == -1)
    {
        inventoryCategorySet.Tables[0].Rows.Add(c.Text.Trim().ToLower());
        inventoryCategorySet.AcceptChanges();
    }
} 

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