首页 > 解决方案 > 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 应用程序

标签: c#datagridview

解决方案


 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);
    }

推荐阅读