2012-02-25 45 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())