How to initialize a DropDownList using 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 initial list returns 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 , this is the same value, the first in the ListItem initlist. There is no property in DDL that contains "Value1". What am I doing wrong, how to insert values ​​correctly so that I can read both values ​​and text?

+5
source share
1 answer

You must set the DataValueField to DropDownList in the Value property for ListItems:

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

Here I also set the DataTextField to the Text property of the elements.

+6
source

Source: https://habr.com/ru/post/1246830/


All Articles