c# - DataGridview 值未清除并添加到新插入的值
问题描述
我有以下代码在gridview中添加值
int row = 0;
dataGridView1.Rows.Add();
row = dataGridView1.Rows.Count-2 ;
dataGridView1["Description",row].Value = prod_name.SelectedItem.ToString();
dataGridView1["Quantity", row].Value = txtQty.Text;
dataGridView1["Price", row].Value = p;
dataGridView1["Discountcell", row].Value = txtdisc_prod.Text;
dataGridView1["amt", row].Value = tot;
为了清除它,我尝试了不同的代码: 1
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
cell.Value = "";
}
}
2
this.dataGridView1.DataSource = null;
this.dataGridView1.Rows.Clear();
dataGridView1.Refresh();
两个代码都清除了值,但是当我添加新值并计算它们时,以前的值也随之添加。以下是我的计算代码:
for (int i = 0; i < dataGridView1.RowCount - 1; i++)
{
float f, d, price;
if (float.TryParse(dataGridView1.Rows[i].Cells["amt"].Value.ToString(), out f))
{
gross_amt = gross_amt + f;
}
if (float.TryParse(dataGridView1.Rows[i].Cells["discountcell"].Value.ToString(), out d))
{
dis_tot = dis_tot + d;
}
}
更新这是 Windows 应用程序
解决方案
Assuming it is a web based application :
You are not binding the grid with null data source:
use this to clear out the data and bind them.
DataTable ds = new DataTable();
ds = null;
grd.DataSource = ds;
grd.Update();
IF you need to remove column name also use the below code snippet:
for (int i = 0; grd.Columns.Count > i; )
{
grd.Columns.RemoveAt(i);
}
推荐阅读
- kubernetes - 如何使用 Terrafom 在 Knative 中启用 AutoTLS?
- python - 如何在open3D中更新圆柱高度
- c++ - 为 N Queen 问题 C++ 制定对角约束
- c - C中二进制文件的动态存储
- android - 我尝试在片段中使用 ScrollView,但它不起作用
- database - 为这个用例建立一个数据库有意义吗?
- post - 如何将对象的 Arraylist 从 java 发送到我的 React 应用程序?
- html - 有没有办法修复chrome中的这个错误?
- qt - 如何初始化 QML 单例?
- oracle - 如何存储和检索临时表中的数据