1

我有一个DataGridView. 我想添加第 4 列值。我写了这段代码。但它显示上面的错误Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);

 decimal Total = 0;

 for (int i = 0; i < dgvSalesFooterAdd.Rows.Count; i++)
 {
      dgvSalesFooterAdd.Rows[i].Cells[4].Value = 
          Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value) * 
          Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value);

          Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[4].Value);
 }
 lblFinalTotalAdd.Text = Total.ToString();

创建第 5 列代码:

            OleDbConnection con = new OleDbConnection(conn);
            con.Open();
            DataTable dtusers = new DataTable();
            OleDbCommand cmd = new OleDbCommand("Select Shorts,Code,Description,Percentage from SalesFields", con);
            OleDbDataAdapter da = new OleDbDataAdapter(cmd);
            da.Fill(dtusers);
            dgvSalesFooterAdd.DataSource = dtusers;
            dgvSalesFooterAdd.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            dgvSalesFooterAdd.Columns[0].Name = "Shorts";
            dgvSalesFooterAdd.Columns[1].Name = "Code";
            dgvSalesFooterAdd.Columns[2].Name = "Description";
            dgvSalesFooterAdd.Columns[3].Name = "Percentage";
            dgvSalesFooterAdd.Columns[0].HeaderText = "Shorts";
            dgvSalesFooterAdd.Columns[1].HeaderText = "Code";
            dgvSalesFooterAdd.Columns[2].HeaderText = "Description";
            dgvSalesFooterAdd.Columns[3].HeaderText = "Percentage";
            DataGridViewColumn amount = new DataGridViewColumn();
            amount.HeaderText = "Amount";
            amount.Name = "Amount";
            amount.CellTemplate = new DataGridViewTextBoxCell();
            dgvSalesFooterAdd.Columns.Insert(4, amount);
            con.Close();

            con.Close();
4

2 回答 2

1

C# 的数组是从零开始的。这意味着第一个元素是元素 0。第四个元素是元素 3。

您可能只有四列,编号为 0 到 3。

于 2013-09-11T18:57:30.200 回答
1

尝试这个,

 decimal Total = 0;

 for (int i = 0; i < dgvSalesFooterAdd.Rows.Count; i++)
 {
      dgvSalesBodyAdd.Rows[i].Cells[3].Value = 
          Convert.ToDecimal(dgvSalesBodyAdd.Rows[i].Cells[2].Value) * 
          Convert.ToDecimal(dgvSalesBodyAdd.Rows[i].Cells[2].Value);

          Total += Convert.ToDecimal(dgvSalesFooterAdd.Rows[i].Cells[3].Value);
 }
 lblFinalTotalAdd.Text = Total.ToString();
于 2013-09-11T18:58:14.783 回答