Inderpal Singh
Inderpal Singh

Reputation: 270

How to add data to GridView?

I'm trying to add data by following code:

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

But as there is no datasource attached to Gridview,This event doesn't fire. Please tell me what to do? Is there anyway to fire this event forcefully or do something else & enter data somewhere else..?

Upvotes: 0

Views: 2054

Answers (1)

gzaxx
gzaxx

Reputation: 17590

You misuse this event and you should not call if forcefully.

First of all somewhere in page_load event load your data and bind it to grid:

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

This will bind your student list to grid. Now we have to handle displaying data on grid, there are more than one ways to do that but this should be enough for you:

In your html, xxx.aspx page where you are declaring your GridView do this:

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

Upvotes: 2

Related Questions