2017-07-24 22 views
0

我的图片如下:计算并插入多个值成列的DataGridView

enter image description here

我想在文本框中的值与上每列值addtion。之后,将总值插入新列(距离)的单元格中,但似乎是不正确的过程。请参考我的代码如下:

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

请帮我指教。非常感谢你。

回答

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 - 列值)以进行求和,而不是仅添加当前列的差异。

+0

嗨,本。谢谢你的建议。它对我的程序很好。谢谢。 – Issac

+0

不客气:) – Ben