簡體   English   中英

如何將數據添加到GridView?

[英]How to add data to GridView?

我正在嘗試通過以下代碼添加數據:

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,因此該事件不會觸發。 請告訴我應該怎么做? 反正有沒有強行發動這個事件或做別的事情並在其他地方輸入數據..?

你濫用這個事件,你不應該強行打電話。

首先在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();
   }
}

這會將您的學生列表綁定到網格。 現在我們必須處理在網格上顯示數據,有多種方法可以做到這一點,但這應該足夠你了:

在您的html,xxx.aspx頁面中,您聲明GridView執行此操作:

<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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM