2013-03-25 4 views
0

4 열이있는 간단한 dataGridView가 있습니다. 세 번째 열의 값을 합하여 결과를 변수에 저장하려고합니다. 이런 식으로 시도했지만 항상 오류 메시지가 표시됩니다.DataGridView의 특정 열의 값을 요약하십시오.

"지정된 캐스트가 유효하지 않습니다. 숫자로 캐스트 할 때 값은 무한대보다 작아야합니다."

P. 각 셀은 기본적으로 DataGridViewTextBoxColumn이며 값을 직접 입력 할 수 있습니다.

코드 :

private void button2_Click(object sender, EventArgs e) 
    { 
     Double result = 0; 
     foreach (DataGridViewRow row in this.dataGridView1.Rows) 
     { 
      result += (Double)row.Cells[2].Value; 
     } 

     this.label13.Text = result .ToString(); 
    } 

나는 무엇을 놓치고?

답변

1

오히려 캐스팅보다`column_name` 만`때문에`잘못된 캐스트 사양에 null` 값이있는 경우이 실패합니다

if (row.Cells[2].Value != null) 
{ 
    try 
    { 
     result += Convert.ToDouble(row.Cells[2].Value); 
    } 
    catch { } 
} 
0
DataTable dt =DataGridView1.DataSource as DataTable; 

decimal total; 

total=(int)dt.Compute("sum(column_name)",""); 
+0

오류 검사와

result += Convert.ToDouble(row.Cells[2].Value); 

시도 ' –

0
private getColSum() 
{ 
    int sum = 0; 
    for (int i = 0; i < dataGridView1.Rows.Count; ++i) 
    { 
     sum += Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value); 
    } 
    return sum; 
} 
관련 문제