karan k
karan k

Reputation: 967

Set all values in SelectList in C#

In a SelectList object, I want that the Text property of each element of the SelectList should also be the value. For eg:

SelectList s=new SelectList(some list);
s.ElementAt(i).Value=s.ElementAt(i).Text;

Is there any way to do this APART from using a loop? Is there any inbuilt method or something like that to accomplish this?

Upvotes: 0

Views: 467

Answers (2)

Oskar Kjellin
Oskar Kjellin

Reputation: 21880

If you really want to do it without a loop, just use linq foreach (which is a loop in the background):

s.ToList().ForEach(c=>c.Text = c.Value)

Upvotes: 1

Ebad Masood
Ebad Masood

Reputation: 2379

You can use the following Constructor overload for SelectList:

public SelectList(
    IEnumerable items,
    string dataValueField,
    string dataTextField
)

You can then, provided same list member for dataValueField and dataTextField.

Upvotes: 1

Related Questions