DataGridView ComboBox列不接受新值 [英] DataGridView ComboBox column not accepting new values
问题描述
我的Windows窗体应用程序中有一个 DataGridView
控件,允许用户编辑产品列表。要编辑产品类别,我希望用户添加新条目或从之前输入的条目中选择。为了实现这一点,我添加了一个 comboBox
列,该列绑定到 DataSource
,从产品表中获取不同的类别名称。在其他一些问题的帮助下,我可以使用以下代码使 comboBox
可编辑:
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;
}
}
但问题是当我尝试编辑类别 comboBox
列,并添加除列表以外的新类别,当我切换到其他单元格时,将切换回现有产品的旧类别项目或新产品的空白。请告诉我如何通过这个 comboBox
列添加新的类别?
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?
推荐答案
最后我自己解决了。我实现了 comboBox
的 LostFocus
事件,其中我添加了更新绑定的 DataSet的代码
与新项目。
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.
该项目已成功添加,但仍有一个问题仍然存在。添加后项目未被选中。 ComboBox
仍然重置为上一个选择。但是,我可以手动选择新项目。但是,如果您可以解决这个错误,它将成为用户更好的UX。以下是我如何实现新项目添加:
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();
}
}
这篇关于DataGridView ComboBox列不接受新值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!