1

I added some custom attributes to checkboxlist, but I wonder why I failed to retrieve the values of custom attributes. It will be something like this post jQuery - find control using custom attribute. But what I want is retrieve through auto postback and code behind.

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"]));     
    }
}
Community
  • 1
  • 1
SƲmmēr Aƥ
  • 2,374
  • 6
  • 24
  • 29
  • 1
    possible duplicate of [ListItems attributes in a DropDownList are lost on postback?](http://stackoverflow.com/questions/1313447/listitems-attributes-in-a-dropdownlist-are-lost-on-postback) – Tim Schmelter Feb 25 '12 at 23:11
  • 1
    You might want to use [this approach](http://stackoverflow.com/a/3099755/284240) to enable your ListItem's attributes to be serialized in ViewState. Anyway, this is a duplicate from that question. – Tim Schmelter Feb 25 '12 at 23:12

1 Answers1

3

The link provided by Tim will probably solve your problem. Just a note on your programming style. This temp variable looks very strange. Try this

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

It is easier an more comprehensible.

And replace this

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

By this

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

Creating an item will look much prettier like this

string caption = String.Format(
    "{0} {1} X {2}", 
    rows1["name"], 
    rows1["quota"],
    rows1["price"]
);
var listItem = new ListItem(caption, rows1["id"].ToString())
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188