我正在学习如何在Visual Studio(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);
和
private void LastColumnComboSelectionChanged(object sender, EventArgs e)
{
string itemValue = GridSellProducts.Rows[GridSellProducts.CurrentCell.RowIndex].Cells["Item"].FormattedValue.ToString();
// get item price
foreach (var item in itemListing)
{
if (item.name == itemValue)
{
unitPrice = item.selling;
break;
}
}
}
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;
}
}
我相信这是string itemValue
总是返回“”的原因(行添加)。我需要获取itemValue才能设置合适的价格。
导致行添加的原因是什么?
答案 0 :(得分:2)
当您的用户可能向网格添加新行时,这是默认行为。插入的行称为NewRow
,等待新输入。要禁用此功能,您必须将AllowUserToAddRows
设置为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;
}
}