简体   繁体   English

DataGridView ComboBox 列不接受新值

[英]DataGridView ComboBox column not accepting new values

I have a DataGridView control in my Windows Forms application that allows users to edit product listing.我的 Windows 窗体应用程序中有一个DataGridView控件,它允许用户编辑产品列表。 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.为了实现这一点,我添加了一个绑定到DataSource的组合comboBox列,该DataSource从产品表中获取不同的类别名称。 With the help of some other SO questions I was able make this comboBox editable using this code:在其他一些 SO 问题的帮助下,我能够使用以下代码使这个组合comboBox可编辑:

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.但问题是,当我尝试编辑类别组合comboBox列并添加未列出的新类别时,当我切换到其他单元格时,它会切换回现有产品的旧类别项目或新产品的空白。 Please tell me how can I add new category through this comboBox column?请告诉我如何通过此组合comboBox列添加新类别?

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.我实现了LostFocus的事件comboBox ,我添加的代码更新绑定DataSet的新项目。

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. ComboBox仍会重置为之前的选择。 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();
    }
} 

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

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