2013-02-09 39 views
0

我想通過下面的代碼添加數據:如何添加數據到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,此事件不火。 請告訴我該怎麼辦? 有沒有辦法強行啓動這個事件或者做其他事情&在其他地方輸入數據..?

+0

我不能添加它..它說gridview1不在當前上下文頁面加載.. – 2013-02-09 08:30:28

回答

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

這將綁定你的學生名單電網。現在,我們必須處理上顯示網格數據,有超過一個的方式來做到這一點,但是這應該給你足夠:

在你的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> 
相關問題