如何在gridview列中添加不同的时间并在页脚文本框中显示总和

时间:2012-10-12 15:51:11

标签: c# asp.net

我在gridview的列(日期时间)中有一些值(08:12,09:22,01:09) 我想要的是在该列的页脚中的文本框中获取该列中存在的所有值的总和。

我尝试了以下代码 -

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

但它不起作用!

3 个答案:

答案 0 :(得分:2)

您可以使用 - 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));

答案 1 :(得分: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();

答案 2 :(得分:1)

使用TimeSpan的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);