在datagridview中计算并将多个值插入到列中

时间:2017-07-24 04:55:32

标签: c# datagridview

我的照片如下:

enter image description here

我想在textbox上获取值,并在每列上添加每个值。之后,将总值插入新列的单元格(距离),但这似乎是不正确的过程。请参考我的代码如下:

int sum =0;

private void btnClassification_Click(object sender, EventArgs e)
{               
    try
    {                            

        dataGridView.Columns.Add("DISTANCE", "DISTANCE");  //add new column             
        int temp,col1, col2, col3,col4,col5;
        col1 = Convert.ToInt16(txtCustAge.Text);
        col2 = Convert.ToInt16(txtCustGender.Text);
        col3 = Convert.ToInt16(txtIssueDate.Text);
        col4 = Convert.ToInt16(txtCustAnnSalary.Text);
        col5 = Convert.ToInt16(txtCustCrlimit.Text);
        for (int rows = 0; rows < dataGridView.Rows.Count; rows++)
        {
            for (int col = 0; col < (dataGridView.Rows[rows].Cells.Count)-2; col++)
            {
                temp = Convert.ToInt16(dataGridView.Rows[rows].Cells[col].Value.ToString());
                sum = sum + ((col1-temp)*(col1-temp) + (col2 - temp)*(col2 - temp) + (col3 - temp)*(col3 - temp) + (col4 - temp)*(col4 - temp) + (col5 - temp)*(col5 - temp));                                                                  
            }
            this.dataGridView.Rows[rows].Cells[6].Value = sum;   // insert total amount into new column                 
            sum = 0;                    
        }            
    }
    catch (Exception ex)
    {
        MessageBox.Show("Please try again !" + ex);
    }
}

请帮忙为我提供建议。非常感谢你。

1 个答案:

答案 0 :(得分:0)

以下内容可以解决您的问题。

dataGridView.Columns.Add("DISTANCE", "DISTANCE");  //add new column             
int temp, col1, col2, col3, col4, col5;
col1 = Convert.ToInt16(txtCustAge.Text);
col2 = Convert.ToInt16(txtCustGender.Text);
col3 = Convert.ToInt16(txtIssueDate.Text);
col4 = Convert.ToInt16(txtCustAnnSalary.Text);
col5 = Convert.ToInt16(txtCustCrlimit.Text);
for (int rows = 0; rows < dataGridView.Rows.Count; rows++)
{
    sum = col1 - Convert.ToInt16(dataGridView.Rows[rows].Cells[0].Value.ToString());
    sum += col2 - Convert.ToInt16(dataGridView.Rows[rows].Cells[1].Value.ToString());
    sum += col3 - Convert.ToInt16(dataGridView.Rows[rows].Cells[2].Value.ToString());
    sum += col4 - Convert.ToInt16(dataGridView.Rows[rows].Cells[3].Value.ToString());
    sum += col5 - Convert.ToInt16(dataGridView.Rows[rows].Cells[4].Value.ToString());
    this.dataGridView.Rows[rows].Cells[6].Value = sum;   // insert total amount into new column                 
    sum = 0;
}

在您的代码中,当您浏览每行的列列表时,您犯了一个错误。您将所有差异(col1,col2,col3,col4,col5 - 列值)添加到sum中,而不是仅添加当前列的差异。