如何使 DataGridView 变为 "increase" 而不是重复
How to make DataGridView to "increase" and not duplicate
我有一个带有 3 个参数的方法,用于向 DataGridView 添加行:
public void DGVadd(string item, int count, int price)
{
DataGrid.Rows.Add(item, count, price);
DataGrid.Update();
}
我通过简单的点击按钮来调用方法:
private void button1_Click(object sender, EventArgs e)
{
DGVadd("item1", 1, 10);
}
问题是:我应该怎么做才能使具有相同名称的项目不会在 DataGridView 中占用多行,只有 1 行并使“计数”和“价格”上涨?
感谢您的宝贵时间!
您需要遍历 DataGrid 的行并检查该项目是否存在。
很久没有使用 WinForms 了,但会是这样的(它只是一个伪代码)
DGVadd(string item, int count, int price)
{
bool newRow = true;
foreach (DataRow row in DataGrid.Rows)
{
if (row.item.Equals(item)
{
row.count += count;
row.price += price;
newRow = false;
}
}
if (newRow)
{
DataGrid.Rows.Add(item, count, price);
}
DataGrid.Update();
}
记住这只是一个伪代码,其中包含我所指的逻辑
我有一个带有 3 个参数的方法,用于向 DataGridView 添加行:
public void DGVadd(string item, int count, int price)
{
DataGrid.Rows.Add(item, count, price);
DataGrid.Update();
}
我通过简单的点击按钮来调用方法:
private void button1_Click(object sender, EventArgs e)
{
DGVadd("item1", 1, 10);
}
问题是:我应该怎么做才能使具有相同名称的项目不会在 DataGridView 中占用多行,只有 1 行并使“计数”和“价格”上涨?
感谢您的宝贵时间!
您需要遍历 DataGrid 的行并检查该项目是否存在。
很久没有使用 WinForms 了,但会是这样的(它只是一个伪代码)
DGVadd(string item, int count, int price)
{
bool newRow = true;
foreach (DataRow row in DataGrid.Rows)
{
if (row.item.Equals(item)
{
row.count += count;
row.price += price;
newRow = false;
}
}
if (newRow)
{
DataGrid.Rows.Add(item, count, price);
}
DataGrid.Update();
}
记住这只是一个伪代码,其中包含我所指的逻辑