日期:2014-05-17  浏览次数:20432 次

这个循环应该怎么写?
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
int s7=4;
if (e.Row.RowType == DataControlRowType.DataRow)
  {
  e.Row.Cells.Add(new TableCell());
  e.Row.Cells[s7].Attributes.Add("rowspan", "1");
  for (int i = 0; i < GridView1.Rows.Count; i++)
  {
  GridView1.Rows[i].Cells[s7].Text = (Convert.ToInt32(GridView1.Rows[i].Cells[1].Text) + Convert.ToInt32(GridView1.Rows[i].Cells[2].Text) + Convert.ToInt32(GridView1.Rows[i].Cells[3].Text)).ToString();

  }
  }




  }
补充:
GridView1.Rows[i].Cells[s7].Text=(Convert.ToInt32(GridView1.Rows[i].Cells[1].Text)+省略号+(Convert.ToInt32(GridView1.Rows[i].Cells[s7-1].Text)).ToString();



我想问的是,假如s7是未知数,那么下面的那个循环语句中的语句应该怎么写?
 for (int i = 0; i < GridView1.Rows.Count; i++)
  {
 GridView1.Rows[i].Cells[s7].Text = (Convert.ToInt32(GridView1.Rows[i].Cells[1].Text) + Convert.ToInt32(GridView1.Rows[i].Cells[2].Text) + Convert.ToInt32(GridView1.Rows[i].Cells[3].Text)).ToString();


  }

------解决方案--------------------
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int count=0;
for(int i=0;i<e.Row.Cells.Count;i++)
{
count+=Convert.ToInt32(e.Row.Cells[i].Text);
}
}
}

例子
HTML code
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

  protected void Page_Load(object sender, EventArgs e)
  {
    if (!Page.IsPostBack)
    {

      System.Data.DataTable dt = new System.Data.DataTable();
      System.Data.DataRow dr;
      dt.Columns.Add(new System.Data.DataColumn("A", typeof(System.Int32)));
      dt.Columns.Add(new System.Data.DataColumn("B", typeof(System.Int32)));
      dt.Columns.Add(new System.Data.DataColumn("C", typeof(System.Int32)));
      dt.Columns.Add(new System.Data.DataColumn("Count", typeof(System.Int32)));

      System.Random rd = new System.Random(Environment.TickCount); ;

      for (int i = 0; i < 8; i++)
      {
        dr = dt.NewRow();
        dr[0] = i;
        dr[1] = i*i;
        dr[2] = i*2;
        dr[3] = 0;
        dt.Rows.Add(dr);
      }
      GridView1.DataSource = dt;
      GridView1.DataBind();
    }
  }


  protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
  {
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
      int totalCount = 0;
      for (int i = 0; i < e.Row.Cells.Count - 1; i++)
      {
        totalCount += Convert.ToInt32(e.Row.Cells[i].Text);
      }
      e.Row.Cells[3].Text = totalCount.ToString();
    }
  }

</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true" OnRowDataBound="GridView1_RowDataBound">
  </asp:GridView>
  </form>
</body>
</html>