a blog for those who code

Thursday 20 July 2017

How to Solve Data Source for GridView did not have any Properties or Attributes

In this post we will be discussing about solving "The data source for GridView with id 'TeamGridView' did not have any properties or attributes from which to generate columns. Ensure that your data source has content." This error comes when you try to bind GridView with a list having a custom class.

Problem Statement

For Example you have created a Class called TeamMember having following fields

public class TeamMember
{
  public int EmployeeId;
  public double Rate;
  public int Hour;
  public double Total;
}


And then you have created a List for binding it to the GrirdView as shown below :

//Initializing List
List<TeamMember> TeamMemberList = new List<TeamMember>();
//Creating Instance of TeamMember Class
TeamMember tm = new TeamMember();
tm.EmployeeId = 123;
tm.Rate = 10.0;
tm.Hour = 10;
tm.Total = 100.0;
TeamMemberList.Add(tm);
//Binding List to the gridView
TeamGridView.DataSource = TeamMemberList;
TeamGridView.DataBind();


So in the above binding step you will get the error as

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

at System.Web.UI.WebControls.GridViewColumnsGenerator.CreateAutoGeneratedFields(Object dataObject, Control control)
at System.Web.UI.WebControls.AutoFieldsGenerator.GenerateFields(Control control)
at System.Web.UI.WebControls.GridView.CreateColumns(PagedDataSource dataSource, Boolean useDataSource)
at System.Web.UI.WebControls.GridView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding)
at System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data)
at System.Web.UI.WebControls.GridView.PerformDataBinding(IEnumerable data)
at System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data)
at System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback)
at System.Web.UI.WebControls.DataBoundControl.PerformSelect()
at System.Web.UI.WebControls.BaseDataBoundControl.DataBind()
at System.Web.UI.WebControls.GridView.DataBind()

Solution

To solve this error you need to change all the fields inside your class to properties as the databinding only can bind against properties and not fields. Thus you need to change the class as shown below thus helps you to successfully bind the list to the GridView.

public class TeamMember
{
  public int EmployeeId { get; set; }
  public double Rate { get; set; }
  public int Hour { get; set; }
  public double Total { get; set; }
}

Please like and share the CodingDefined.com blog if you find it useful and helpful.

No comments:

Post a Comment