C# checkboxlist的自定义属性

C# checkboxlist的自定义属性,c#,asp.net,custom-attributes,C#,Asp.net,Custom Attributes,我向checkboxlist添加了一些自定义属性,但我想知道为什么检索自定义属性的值失败。它将类似于这篇文章。但我想要的是通过自动回发和代码隐藏进行检索 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(

我向checkboxlist添加了一些自定义属性,但我想知道为什么检索自定义属性的值失败。它将类似于这篇文章。但我想要的是通过自动回发和代码隐藏进行检索

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"]));     
    }
}

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"])
创建一个项目会像这样看起来更漂亮

string caption = String.Format(
    "{0} {1} X {2}", 
    rows1["name"], 
    rows1["quota"],
    rows1["price"]
);
var listItem = new ListItem(caption, rows1["id"].ToString())
您可能希望使用的的可能重复项,以使ListItem的属性能够在ViewState中序列化。无论如何,这是一个重复的问题。