DataGridView ComboBox column not accepting new values

可紊 提交于 2019-12-13 02:25:44

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/36679164/datagridview-combobox-column-not-accepting-new-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!