How to save a third value in each ListItem of an ASP.NET dropdownlist?
asp.net
Solution
If you are using a binded `DropDownList`, defined with the `DataTextField` and `DataValueField` properties, there's not really a good way to save the third value on the `DropDownList` itself. You could save it separately tho.
If you're defining your `DropDownList` through the markup, you could try defining it as a custom attribute:
<asp:DropDownList ID="ddlDummy" runat="server">
<asp:ListItem Text="x" Value="y" ThirdValue="z" />
</asp:DropDownList>
For retrieving it, you could use FindByValue and get the `ThirdValue` attribute from the ListItem:
ListItem item = ddlDummy.Items.FindByValue("y");
string value = item.Attributes["ThirdValue"];
However, weirdly, if you generate the items dynamically, the attributes will not be persisted:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ListItem item = new ListItem("x", "y");
item.Attributes.Add("ThirdValue", "z");
ddlDummy.Items.Add(item);
}
}
If this is your case, you could take a look at this question that gives a work arround:
ListItems attributes in a DropDownList are lost on postback?
Problem
Each ListItem in an ASP.NET has a value property and a text property. I need to have a third value saved also. My hack is to concatenate a special separator and the third value to the Value property. But using FindByValue method makes this cumbersome. Is there a better way to save the third value or a good way to use FindByValue. (I can't use FindByText). I wish there was a Tag property.