bind list to dropdownlist, what to do with value?

2019-06-20 18:53发布

问题:

I am binding a List to a DropDownList. But I want to give other values to the value per list item.

I have following ddl and list:

List<string>

sport, volleyball, rugby

<select>
    <option selected="selected" value="0"> Alle soorten</option>
    <option value="sport">sport</option>
    <option value="volleyball">volleyball</option>
    <option value="rugby">rugby</option>
</select>

But I want following (ID in the value)

<select>
    <option selected="selected" value="0"> Alle soorten</option>
    <option value="1">sport</option>
    <option value="2">volleyball</option>
    <option value="3">rugby</option>
</select>

How do I need to create a List so I can get the above dropdownlist.

Thanks

回答1:

If you are able to change the type of your source I would recommend to use a dictionary. You can do it this way:

var source = new Dictionary<int, string>();
source.Add(0, "Sports");
source.Add(1, "Football");
dropDown.DataSource = source;
dropDown.DataTextField = "Key";
dropDown.DataValueField = "Value";
dropDown.DataBind();

This would lead to this:

<select name="DdlCat2" id="DdlCat2" class="cats">
    <option selected="selected" value="Sports">0</option>
    <option value="Football">1</option>
</select>

Later you can access the ID or value like this:

dropDown.SelectedItem.Value
dropDown.SelectedItem.Text


回答2:

What you could do is to create the ListItems manually like this:

List<string> yourValues;
for(var i=0; i < yourValues.Count; i++)
    YourDropDown.Items.Add(new ListItem(yourValues[i], i.ToString());

Or you could create a temporary variable and bind your drop down list with a linq query, like this:

List<string yourValues;
var index = 0;
YourDropDown.DataSource = yourValues.Select(x => new { Text = x, Value = index++ });
YourDropDown.DataBind();

and combine that with the markup:

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


回答3:

Here is the one more way. Convert the DataSet Table to list and bind to dropdown.

var filter = from dr in ds.Tables[0].AsEnumerable()
            where (dr.Field<int>("FilterID") == 1)
            select new
            {
                FilterID = dr.Field<int>("FilterID"),
                FilterName = dr.Field<string>("FilterName")
            };

ddlSample.DataSource = filter;
ddlSample.DataTextField = "FilterName";
ddlSample.DataValueField = "FilterID";
ddlSample.DataBind();
filter = null; // null the var