4

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.

Tony_Henrich
  • 37,447
  • 63
  • 211
  • 355

1 Answers1

4

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?

Community
  • 1
  • 1
Mt. Schneiders
  • 4,568
  • 3
  • 17
  • 40