DataGridview值未清除并添加到新插入的值

时间:2019-04-12 11:49:17

标签: 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应用程序

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您要在哪里声明Gross_amt和dis_tot?您是否在运行for循环之前将它们重置为0(或您想要的默认数字)?如果没有的话,它们只会继续从上一个循环中添加。