[英]Binding CheckBoxList to a Generic List
How to bind a CheckBoxList to a generic list object. 如何将CheckBoxList绑定到通用列表对象。 This sample code should work for the purpose:
此示例代码应满足以下目的:
protected void Page_Load(object sender, EventArgs e)
{
// Works well with the datatable as a data source
//DataTable _entityList = new DataTable();
//_entityList.Columns.Add("Id", typeof(int));
//_entityList.Columns.Add("ProductName", typeof(string));
//_entityList.Rows.Add(new object[] { 1, "First" });
//_entityList.Rows.Add(new object[] { 2, "Second" });
// Doesn't work with the generic list as a data source
List<MyProduct> _entityList = new List<MyProduct>();
_entityList.Add(new MyProduct(1, "First"));
_entityList.Add(new MyProduct(2, "Second"));
cblProducts.DataSource = _entityList;
cblProducts.DataTextField = "ProductName";
cblProducts.DataValueField = "Id";
cblProducts.DataBind();
}
public class MyProduct
{
public int Id;
public string ProductName;
public bool selected;
public MyProduct(int id, string desc, bool slctd)
{
this.Id = id;
this.ProductName = desc;
this.selected = slctd;
}
public MyProduct()
{
// TODO: Complete member initialization
}
}
But it is throwing a run time exception: 但这会引发运行时异常:
DataBinding: 'Test.MyProduct' does not contain a property with the name 'ProductName'. 数据绑定:'Test.MyProduct'不包含名称为'ProductName'的属性。
What am I missing? 我想念什么? I tried google the topic but failed.
我尝试了谷歌的话题,但失败了。
Change your fields to properties: 将字段更改为属性:
public class MyProduct
{
public int Id { get; set; }
public string ProductName { get; set; }
public bool selected { get; set; }
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.