2015-04-14 20 views
1

早上好;測試DataGridView中最後輸入的空白​​對象

我收到了一些奇怪的行爲,使用DataSet將DataGridView導入到DataGridView,在DataGridView中測試空白對象值。我剛開始研究在我的WinForm中使用DataGridView。我創建使用AuthorsDataSet非常簡單的DataGridView演練

https://msdn.microsoft.com/en-us/library/ekw4dh3f.aspx

然後我操縱的代碼,非常minorly,讀我的XML文件,而不是AuthorsDataSet。很棒。

然後我嘗試將一列中的所有項目求和。我發現這一點,它讓我明白了我的觀點。

how I can show the sum of in a datagridview column?

這使我在這裏

public string sum() 
    { 

     double sum = 0; 
     for (int i = 0; i < dataGridView1.Rows.Count; ++i) 
     { 
      var test = dataGridView1.Rows[i].Cells[6].Value; //Can not use 
       //double here as I get the FromatException whether 
       //testing for `==null` or `==""` 

      //double test = Convert.ToDouble(dataGridView1.Rows[i].Cells[6].Value); THIS THROWS FormatException 

      if (test == "") 
      { 
       sum += 0; 
      } 
      else 
      { 
       sum += Convert.ToDouble(test); 
      } 
     } 
     return sum.ToString(); 
    } 

如果我使用double test...if (test == null)我得到FormatException was unhandled最後我有什麼作品,但我擔心在未來其他錯誤。關注點在於我測試的xml對象可能沒有價值,我不確定該去哪裏。我應該爲它賦值0,然後在用戶提供輸入時寫上它(在這種情況下,它是一個簡單的啓動/停止計時器)。

如果我只使用sum += Convert.ToDouble(dataGridView1.Rows[i].Cells[6].Value);而未測試空白xml對象, FormatException錯誤。

我怎麼測試這個不正確。示例xml條目如下:

<?xml version="1.0" encoding="utf-8"?> 
<Form1> 

    <Name Key="4/13/2015 3:22:05 PM"> 
    <Date>4/13/2015</Date> 
    <JobNum>01det</JobNum> 
    <RevNum>00000</RevNum> 
    <Task>testing</Task> 
    <Start>12:30 PM</Start> 
    <End>03:22 PM</End> 
    <TotalTime>9828063</TotalTime> 
    </Name> 
    <Name Key="4/14/2015 6:36:06 AM"> 
    <Date>4/14/2015</Date> 
    <JobNum>01det</JobNum> 
    <RevNum>00000</RevNum> 
    <Task>testing</Task> 
    <Start>06:36 AM</Start> 
    <End></End> \\THIS ONE WILL ALMOST ALWAYS BE BLANK DURING REGULAR BUSINESS HOURS 
    <TotalTime></TotalTime> 
    </Name> 
</Form1> 

請提前通知並感謝您。我很感激!!

回答

2

試試這個。

public string sum() 
    { 
     double sum = 0; 
     string test; 
     for (int i = 0; i < dataGridView1.Rows.Count; ++i) 
     { 
      if (dataGridView1.Rows[i].Cells[6].Value != null) 
      { 
       test = dataGridView1.Rows[i].Cells[6].Value.ToString(); 

       if (test != "") 
       { 
        sum += double.Parse(test); 
       } 
      }     
     } 
     return sum.ToString(); 
    } 
+0

'string test = dataGridView1.Rows [i] .Cells [6] .Value.ToString();'給我提供了一個NullReference異常在有問題的xml。謝謝你:-) – Frank

+0

現在試試這個。我更新了我的答案。 – Eplzong

+0

這看起來非常好。我忘記了聲明字符串然後分配它。我不會爲了生活而編碼,所以可能會有幾個月的時間。謝謝。你拿到了獎品,但我一定會提供更多的反饋意見。謝謝!! :-D – Frank