asp.netdrop-down-menu

How to initialize DropDownList with ListItems


I am trying to initialize a DropDownList and this is my select method:

public List<ListItem> metodShownAbove()
{
    List<ListItem> initlist = new List<ListItem>();
    if (!IsPostBack)
    {
        initlist.Add(new ListItem("--- all---", "-1"));
        initlist.Add(new ListItem("text1", "Value1"));
        initlist.Add(new ListItem("text2", "Value2"));
        initlist.Add(new ListItem("text3", "Value3"));
    }
    return initlist;
}

And this is on my aspx page:

<asp:DropDownList ID="DDL" runat="server" AutoPostBack="True" 
    SelectMethod="metodShownAbove"/> 

The initlist is returning what I want to return, text and value as shown above. But when I try to get the selected value or text, DDL.SelectedItem.Value and DDL.SelectedItem.Text, it is the same value, the first one in ListItem initlist. There is no property in DDL which contains 'Value1'. What am I doing wrong, how to correctly insert values, so that I can read both, value and text?


Solution

  • You must set the DataValueField of the DropDownList to the Value property of the ListItems:

    <asp:DropDownList ID="DDL" runat="server" DataTextField="Text" DataValueField="Value" ... />
    

    Here I also set the DataTextField to the Textproperty of the items.