C# 在DataGridView中的combobox单元格上进行选择将添加新行

C# 在DataGridView中的combobox单元格上进行选择将添加新行,c#,datagridview,C#,Datagridview,我正在学习如何在VisualStudio(Winforms)中使用datagridview,但遇到了这个问题 当我运行程序,单击第一列(包含一个名为Item的组合框列)并选择第一行单元格并进行选择时,一个新行将自动添加到它下面,这是我不希望发生的 我的代码: // set values to combobox column cells in datagridview DataGridViewComboBoxColumn cmbItems = (DataGridViewComboBoxColumn

我正在学习如何在VisualStudio(Winforms)中使用datagridview,但遇到了这个问题

当我运行程序,单击第一列(包含一个名为Item的组合框列)并选择第一行单元格并进行选择时,一个新行将自动添加到它下面,这是我不希望发生的

我的代码:

// set values to combobox column cells in datagridview
DataGridViewComboBoxColumn cmbItems = (DataGridViewComboBoxColumn)GridSellProducts.Columns["Item"];

cmbItems.DataSource = productNames;
cmbItems.AutoComplete = true;

GridSellProducts.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(GridSellProducts_EditingControlShowing);

我相信这就是
string itemValue
总是返回“”的原因(行添加)。我需要得到itemValue,以便设置适当的价格。
导致行添加的原因是什么?

当用户可以向网格中添加新行时,这是默认行为。插入的行被称为等待新输入的
NewRow
。要禁用此功能,您必须将
allowUserToAddress
设置为false,但这样您就必须实现添加新行的逻辑

还要注意以这种方式向内部控制添加事件:

private void GridSellProducts_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
     if (GridSellProducts.CurrentCell.ColumnIndex == 0 && e.Control is ComboBox)
     {
          ComboBox comboBox = e.Control as ComboBox;
          comboBox.SelectedIndexChanged += LastColumnComboSelectionChanged;
     }
}
起初看起来还可以,但每次单击组合框时,都会添加新的事件处理程序,导致触发多次!正确的方法:

private void GridSellProducts_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
     if (GridSellProducts.CurrentCell.ColumnIndex == 0 && e.Control is ComboBox)
     {
          ComboBox comboBox = e.Control as ComboBox;
          comboBox.SelectedIndexChanged -= LastColumnComboSelectionChanged; //remove event if it was added before
          comboBox.SelectedIndexChanged += LastColumnComboSelectionChanged;
     }
}

是否要求网格是可编辑的?否则,将其设置为只读,这将解决此问题。您是否可以尝试将
allowUserToAddress
设置为
false
?网格是一个销售项目表单,允许用户编辑单元格,例如数量,并允许他们为库存中的不同项目添加行。
private void GridSellProducts_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
     if (GridSellProducts.CurrentCell.ColumnIndex == 0 && e.Control is ComboBox)
     {
          ComboBox comboBox = e.Control as ComboBox;
          comboBox.SelectedIndexChanged -= LastColumnComboSelectionChanged; //remove event if it was added before
          comboBox.SelectedIndexChanged += LastColumnComboSelectionChanged;
     }
}