问题描述
|
我的问题是如何使用下面的代码对datagridview进行数据绑定。请检查一下..谢谢!
InsuranceLabel oInsurance = new InsuranceLabel(); //Retrieves the list of existing Insurance from my database
oInsurance.Name = GrdInsurance.Columns(0).text; //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();
我希望你能帮助我..谢谢!
解决方法
网格视图需要对象的集合,而不是单个对象。
但是,作为解决方法,您可以创建一个IncuranceLabel列表,然后将对象添加到其中。
List<IncuranceLabel> items = new List<IncuranceLabel>();
items.add(oInsurance);
grdInsurance.DataSource = items;
grdInsurance.Databind();
,创建一个Collection类并将其作为数据源
grdInsurance.DataSource = CollectionClass;
grdInsurance.Databind();
,不要忘记设计您的类,这样属性才是真正的属性,而不是字段。
例如,不要做:
// Bad example: all of these are Fields,not Properties
public class InsuranceLabel
{
public string Name;
public string City;
public string Category;
}
相反,请执行以下操作:
// 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; }
}