0

我正在尝试通过以下代码添加数据:

protected  void gridview1_RowCreated(object sender, GridViewRowEventArgs e)
{
  if (e.Row.RowType == DataControlRowType.DataRow)
  {
    if (Session["BranchingCode"] != null)
    {
      List<CourseDetail> studentList = Course_Detail.GetStudentListOfBranch(Session["BranchingCode"].ToString(), Session["CurrentSession"].ToString());
      if (studentList != null)
      {
        for (int i = 0; i < studentList.Count(); i++)
        {
           e.Row.Cells[0].Text = studentList[i].UserNameRoll;
           e.Row.Cells[1].Text = studentList[i].StudentName;
        }
      }
    }
    GridView1.DataBind();
  }
}

但由于没有datasource附加到 Gridview,因此不会触发此事件。请告诉我该怎么办?无论如何要强行触发此事件或做其他事情并在其他地方输入数据..?

4

1 回答 1

2

您滥用此事件,如果强行调用,则不应调用。

首先在 page_load 事件的某处加载您的数据并将其绑定到网格:

if (Session["BranchingCode"] != null)
{
   List<CourseDetail> studentList = Course_Detail.GetStudentListOfBranch(Session["BranchingCode"].ToString(), Session["CurrentSession"].ToString());
   if (studentList != null)
   {  
       GridView1.DataSource = studentList;
       GridView1.DataBind();
   }
}

这会将您的学生列表绑定到网格。现在我们必须处理在网格上显示数据,有不止一种方法可以做到这一点,但这对你来说应该足够了:

在您声明 GridView 的 html、xxx.aspx 页面中,执行以下操作:

<asp:GridView ID="GridView1" runat="server" ...... >
   <Columns>
      <asp:BoundField HeaderText="User Name Roll" DataField="UserNameRoll" />
      <asp:BoundField HeaderText="Student Name" DataField="StudentName" />
   </Columns>
</asp:GridView>
于 2013-02-09T09:34:47.407 回答