I'm trying to add items to a dropdown list using a List of ListItems, but it's not picking up the value (only the text).
The code is below (simplified from the code I'm actually using):
PositionDropDown.DataSource = GetPositionOptions();
PositionDropDown.DataBind();
private List<ListItem> GetPositionOptions()
{
List<ListItem> items = new List<ListItem>();
items.Add(new ListItem("",""));
items.Add(new ListItem("Top (main)", "TOP"));
items.Add(new ListItem("Bottom (full width)", "BTM"));
items.Add(new ListItem("Bottom Left", "MIL"));
items.Add(new ListItem("Bottom Middle", "MID"));
return items;
}
However the rendered HTML is missing the values specified in the 2nd parameter of the ListItem constructor:
<option value=""></option>
<option value="Top (main)">Top (main)</option>
<option value="Bottom (full width)">Bottom (full width)</option>
<option value="Bottom Left">Bottom Left</option>
<option value="Bottom Middle">Bottom Middle</option>
Why is it not using the specified "value" and instead just repeating the "name" when rendering the HTML? What am I doing wrong?
Try with this code. You're mixing manually item addition with data binding.
private void SetPositionOptions()
{
PositionDropDown.Items.Add(new ListItem("",""));
PositionDropDown.Items.Add(new ListItem("Top (main)", "TOP"));
PositionDropDown.Items.Add(new ListItem("Bottom (full width)", "BTM"));
PositionDropDown.Items.Add(new ListItem("Bottom Left", "MIL"));
PositionDropDown.Items.Add(new ListItem("Bottom Middle", "MID"));
}
I'd say that if you want to keep your code as it is you should add this 2 lines
PositionDropDown.DataSource = GetPositionOptions();
PositionDropDown.DataTextField = "Text";
PositionDropDown.DataValueField = "Value";
PositionDropDown.DataBind();
But it make no sense, you're not supposed to bind ListItems.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With