2012-02-25 29 views
1

我向复选框列表中添加了一些自定义属性,但我想知道为什么我无法检索自定义属性的值。这将是这样的帖子jQuery - find control using custom attribute。但我想要的是通过自动回发和代码后面检索。复选框列表的自定义属性

int temp = 0; 
foreach (DataRow rows1 in ds_ss_equipments_data.Tables[0].Rows) 
{ 
    cblEquip.Items.Add(new ListItem(rows1["name"].ToString() + " " + rows1["quota"].ToString() + " X " + rows1["price"].ToString(), rows1["id"].ToString())); 
    cblEquip.Items[temp].Attributes["price"] = rows1["price"].ToString(); 
    cblEquip.Items[temp].Attributes["id"] = rows1["id"].ToString(); 
    cblEquip.Items[temp].Attributes["quota"] = rows1["quota"].ToString(); 
    temp += 1; 
} 



foreach (ListItem li in cblEquip.Items) 
{ 
    if (li.Selected) 
    { 
     equip += (Convert.ToDecimal(li.Attributes["price"]) * Convert.ToInt32(li.Attributes["quota"]));  
    } 
} 
+1

的[listItems中可能重复的漂亮多属性都丢失回发?(http://stackoverflow.com/questions/1313447/listitems-attributes-in-a-dropdownlist-are-lost-on-post返回) – 2012-02-25 23:11:22

+1

您可能想要使用[此方法](http://stackoverflow.com/a/3099755/284240)来启用ListItem的属性在ViewState中序列化。无论如何,这个问题是重复的。 – 2012-02-25 23:12:12

回答

3

Tim提供的链接可能会解决您的问题。只是关于你的编程风格的说明。这个temp变量看起来很奇怪。试试这个

foreach (DataRow rows1 in ds_ss_equipments_data.Tables[0].Rows) 
{        
    var listItem = new ListItem(rows1["name"].ToString() + " " + ...) 
    listItem.Attributes["price"] = rows1["price"].ToString(); 
    listItem.Attributes["id"] = rows1["id"].ToString(); 
    listItem.Attributes["quota"] = rows1["quota"].ToString(); 
    cblEquip.Items.Add(listItem); 
} 

这样更容易理解。

而更换此

rows1["name"].ToString() + " " + rows1["quota"].ToString() + " X " + rows1["price"].ToString() 

通过这个

String.Format("{0} {1} X {2}", rows1["name"], rows1["quota"], rows1["price"]) 

创建项目将看在一个DropDownList这样

string caption = String.Format(
    "{0} {1} X {2}", 
    rows1["name"], 
    rows1["quota"], 
    rows1["price"] 
); 
var listItem = new ListItem(caption, rows1["id"].ToString())