【问题标题】:Custom attributes of checkboxlist复选框列表的自定义属性
【发布时间】:2012-02-25 22:37:08
【问题描述】:

我在 checkboxlist 中添加了一些自定义属性,但我想知道为什么我无法检索自定义属性的值。这将类似于这篇文章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"]));     
    }
}

【问题讨论】:

标签: c# asp.net custom-attributes


【解决方案1】:

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())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 2010-10-28
    相关资源
    最近更新 更多