Logo Questions Linux Laravel Mysql Ubuntu Git 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 wich contains 'Value1'. What am I doing wrong, how to correctly insert values, so that I can read both, value and text?

like image 544
1392023093user Avatar asked Apr 10 '16 21:04

1392023093user


1 Answers

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.

like image 182
ConnorsFan Avatar answered Oct 02 '22 15:10

ConnorsFan