views:

1025

answers:

3

Hey there,

another beginner problem. Why isn't the following code with an asp.net page not working?

protected void Page_Load(object sender, EventArgs e)
{
    List<string> list = new List<string>();
    list.Add("Teststring");
    this.GridView.DataSource = list;
}

GridView is the GridView control on that asp page. However, no grid shows up at all. It's both enabled and visible. Plus when I debug, the GridView.Rows.Count is 0. I always assumed you can just add generic Lists and all classes implementing IList as a DataSource, and the gridview will then display the content automatically? Or is the reason here that it's been done in the page_load event handler. and if, how can I fill a grid without any user interaction at startup?

Thanks again.

+4  A: 

You should call DataBind().

Zachary
+3  A: 

You forgot to call the GridView's .DataBind() method. This is what will link the control to its data source and load the results.

Example:

protected void Page_Load(object sender, EventArgs e)
{
    List<string> list = new List<string>();
    list.Add("Teststring");
    this.GridView.DataSource = list;
    this.GridView.DataBind();
}
TheTXI
+2  A: 

Unlike in winforms, for ASP developement you need to specifically call GridView.DataBind();. I would also break out that code into a separate method and wrap the initial call into a check for postback. That will save you some headaches down the road.

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostback)
   {
       List<string> list = new List<string>();
       list.Add("Teststring");
       bindMydatagrid(list);
   }
}

protected void bindMydatagrid(List<string> list)
{
    gv.DataSource = list;
    gv.DataBind();
}
Rob Allen
Thank you all guys, I'm really stupid. Works like a charm now!Btw, what would be the danger if don't check for IsPostback? I think I still haven't got a grip on that one.
noisecoder
@noisecoder - Without the IsPostback check the grid will rebind every time your page refreshes (button clicks, selected index changes... etc).
Rob Allen
Also - the separate method is for easy manually rebinds when the data changes
Rob Allen