How to Databind a DataGridView?
my questions is how to databind a datagridview using my codes below. Please check it.. thanks!
InsuranceLabel oInsurance = new InsuranceLabel(); //Retrieves the list of existing Insurance from my database
oInsurance.Name = grdInsurance.Columns(0).t开发者_开发技巧ext; //Fields Name
oInsurance.City = grdInsurance.Columns(0).text; //Fields City
oInsurance.Category = grdInsurance.Columns(0).text; //Fields Category
grdInsurance.DataSource = oInsurance;
grdInsurance.AutoGenerateColumns = true; //not sure that's the property
grdInsurance.DataBind();
i hope you can help me.. thanks!
The Grid View requires a collection of objects not a single object.
But as a workaround you can Create a List of IncuranceLabel then add your object to it.
List<IncuranceLabel> items = new List<IncuranceLabel>();
items.add(oInsurance);
grdInsurance.DataSource = items;
grdInsurance.Databind();
create a Collection Class and make it as the datasource
grdInsurance.DataSource = CollectionClass;
grdInsurance.Databind();
Do not forget to design your class so properties are true properties and not fields.
For example, dont do :
// Bad example: all of these are Fields, not Properties
public class InsuranceLabel
{
public string Name;
public string City;
public string Category;
}
Instead, do :
// Good example: all of these are Properties
public class InsuranceLabel
{
public string Name { get; set; }
public string City { get; set; }
public string Category { get; set; }
}
精彩评论