2011-04-18 105 views
0

我的问题是如何使用下面的代码对datagridview进行数据绑定。请检查它..谢谢!如何数据绑定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(); 

我希望你能帮助我..谢谢!

+0

你为什么这样做** oInsurance.Name = grdInsurance.Columns(0)的.text; ** ,你有什么错误吗? – V4Vendetta 2011-04-18 05:08:23

回答

4

网格视图需要的对象集合不是单个对象。

但作为一种解决方法,您可以创建一个IncuranceLabel列表,然后将您的对象添加到它。

List<IncuranceLabel> items = new List<IncuranceLabel>(); 
items.add(oInsurance); 
grdInsurance.DataSource = items; 
grdInsurance.Databind(); 
+0

其工作..但它只显示一个字段(代理代码)..名称,城市,类别如何? – 2011-04-18 05:25:17

+0

为了让它显示所有字段,创建一个自定义类,它包含所有需要的字段并覆盖它的ToString()方法,以便它们之间打印所有的字段(inverval,newline等)。当您使用List items = ...一切都会正常工作:) – asenovm 2011-04-18 05:56:08

+0

我不确定此代码是否正常工作: oInsurance.Name = grdInsurance.Columns(0).text; 你可以把一个静态值来测试:oInsurance.Name =“Test”; – 2011-04-19 12:15:35

3

创建一个集合类,并使其作为数据源

grdInsurance.DataSource = CollectionClass; 
grdInsurance.Databind(); 
2

不要忘记这样的属性是真正的性质,而不是字段设计类。

例如,做:

// 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; } 
}