2

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.

3 Answers 3

4

You should call DataBind().

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

2

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

3 Comments

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 - Without the IsPostback check the grid will rebind every time your page refreshes (button clicks, selected index changes... etc).
Also - the separate method is for easy manually rebinds when the data changes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.