Monday, April 4, 2011

C#: GridView

I create a GridView in an asp.net web apge. When it runs method DataBind(), an HttpException is shown as below:

The data source for GridView with id 'GridView1' did not have any properties or attributes from which to generate columns. Ensure that your data source has content.


When assigning a list of custom object to the data source of GridView,  .Net can read the property names of collection objects automatically. 

The above problem can be solved by the following code:

 public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Button1_Click(object sender, EventArgs e)
        {
            ArrayList list = new ArrayList();
            Car c1 = new Car() { Add = "1", Name = "2"};
            list.Add(c1);
            //data grid
            GridView1.AutoGenerateColumns = true;
            GridView1.DataSource = list;
            GridView1.DataBind();
        }
    }
    class Car
    {
        public String Name { get; set;}
        public String Add {get;  set;}
    }
For more detail about GridView in C#: http://www.dotnetperls.com/datagridview-tips

1 comment: