SearchForKnowledge
SearchForKnowledge

Reputation: 3751

How to add items to a string array from a dropdownlist

I have a dropdownlist (specialty) and I want to loop through the number of options in the specialty and add it an array:

string[] strSpecArrayForTopics = new string[Specialty.Items.Count]; //total number of specialty items
foreach (ListItem li in Specialty.Items) //for each item in the dropdownlist
{
    strSpecArrayForTopics[Specialty.Items.Count] = li.Value; //add the value to the array (The error happens here)
    lblSpec.Text = lblSpec.Text + "<br />" + li.Value; //this works fine.
}

So let's say the specialty dropdownlist has:

All
Card
Intern
Rad

The array should be:

strSpecArrayForTopics[0] = "All";
strSpecArrayForTopics[1] = "Card";
strSpecArrayForTopics[2] = "Intern";
strSpecArrayForTopics[4] = "Rad";

Upvotes: 0

Views: 2542

Answers (5)

Grax32
Grax32

Reputation: 4059

You can also use LINQ for this.

using System.Linq;

string[] strSpecArrayForTopics = Specialty.Items.Select(v => v.Value).ToArray();

if .Value is of type object, use the following.

string[] strSpecArrayForTopics = Specialty.Items.Select(v => (string)v.Value).ToArray();

Upvotes: 1

Xiaoy312
Xiaoy312

Reputation: 14477

var strSpecArrayForTopics = Specialty.Items.Cast<ListItem>().Select(x => x.Value).ToArray();

Upvotes: 2

Paresh J
Paresh J

Reputation: 2419

You need to add index to your array. Check the below code:

string[] strSpecArrayForTopics = new string[Specialty.Items.Count]; //total number of specialty items
int index = 0;
foreach (ListItem li in Specialty.Items) //for each item in the dropdownlist
{
    strSpecArrayForTopics[index] = li.Value; //add the value to the array (The error happens here)
    lblSpec.Text = lblSpec.Text + "<br />" + li.Value; //this works fine.
    index = index + 1;
}

Upvotes: 1

SearchForKnowledge
SearchForKnowledge

Reputation: 3751

I also used this as a solution:

string[] strSpecArrayForTopics = new string[Specialty.Items.Count];
int k = 0;
foreach (ListItem li in Specialty.Items)
{

    strSpecArrayForTopics[k] = li.Value;
    lblSpec.Text = lblSpec.Text + "<br />" + li.Value;
    k++;
}

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You are looking for a for loop.

for(int i = 0;i < Specialty.Items.Count; i++) //for each item in the dropdownlist
{
    strSpecArrayForTopics[i] = Specialty.Items[i].Value; 
    lblSpec.Text = lblSpec.Text + "<br />" + Specialty.Items[i].Value; 
}

Upvotes: 1

Related Questions