2012-10-12 56 views
0

我有一些值(08:12,09:22,01:09)在塔(日期時間)在一個gridview
我想要的是在該列的頁腳中存在的文本框中獲得該列中存在的所有值的總和。如何在一個gridview的列添加不同時間存在並顯示文本框頁腳的總和

我嘗試下面的代碼 -

int hours, minutes; 
    TextBox footxt = (TextBox)GridView2.FooterRow.FindControl("footxt1"); 
    foreach (GridViewRow row in GridView2.Rows) 
    { 
     TextBox txts = (TextBox)row.FindControl("text11"); 

     TimeSpan ts = TimeSpan.Parse(txts.Text); 
     hours = ts.Hours; 
     minutes = ts.Minutes; 
     hours += hours; 
     minutes += minutes; 
    footxt.Text = Convert.ToString(hours); 
    } 

但它不工作!

+1

它不工作 - 如何?你能解釋一下嗎? – codingbiz

回答

1

使用時間跨度的operator +

TimeSpan total = new TimeSpan(); 
TextBox footxt = (TextBox)GridView2.FooterRow.FindControl("footxt1"); 
foreach (GridViewRow row in GridView2.Rows) 
{ 
    TextBox txts = (TextBox)row.FindControl("text11"); 
    total += TimeSpan.Parse(txts.Text); 
} 
footxt.Text = Convert.ToString(hours); 
+0

謝謝Tonn!它工作! – TheCode

+0

@MichaelCode,考慮upvoting有用的答案並接受回答你的問題 - 如果你打算提出更多的問題有很多問題沒有被接受的答案會降低獲得良好答案的機會,所以儘早開始:) –

2

您可以將ty有 - hours and hoursCpt

... 
    hours = ts.Hours; 
    minutes = ts.Minutes; 
    hoursCpt += hours; 

所以

int hours, minutes, hoursCpt, minutesCpt; 
hoursCpt = 0; 
minutesCpt = 0; 

TextBox footxt = (TextBox)GridView2.FooterRow.FindControl("footxt1"); 
foreach (GridViewRow row in GridView2.Rows) 
{ 
    TextBox txts = (TextBox)row.FindControl("text11"); 

    TimeSpan ts = TimeSpan.Parse(txts.Text); 
    hours = ts.Hours; 
    minutes = ts.Minutes; 

    hoursCpt += hours; 
    minutesCpt += minutes; 
} 
footxt.Text = Convert.ToString(hoursCpt + ((minutesCpt - minutesCpt % 60)/60)); 
+0

+1正確處理溢出...但TimeSpan +是如此簡單:) –

+0

我試過這個,但它給了我錯誤hoursCpt說未分配的本地變量...我已經在foreach循環之前int int hoursCpt – TheCode

+0

@Michael hoursCpt = 0; –

1

現在你通過每一次覆蓋hours你循環,所以你添加到它,但再擦出來當你回到下一個價值。

int totHours, totMinutes 
TextBox footTxt = (TextBox)GridView2.FooterRow.FindControl("footxt1"); 

foreach (GridViewRow row in GridView2.Rows) 
{ 
    TextBox txts = (TextBox)row.FindControl("text11"); 
    TimeSpan ts = TimeSpan.Parse(txts.Text); 

    totHours += ts.Hours; 
    totMinutes += ts.Minutes; 

} 
footTxt.Text = totHours.ToString(); 
相關問題