0

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";
1
  • What is your question? What is the error? Think about that, and I think you might get a hand of it yourself ... Commented Jan 14, 2015 at 14:50

5 Answers 5

2
var strSpecArrayForTopics = Specialty.Items.Cast<ListItem>().Select(x => x.Value).ToArray();
Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

2 Comments

I beat you to it ;) Thanks for your response though.
@SearchForKnowledge: Yeah!!! Great to found your answer on your own. Great job!!!
1

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; 
}

Comments

1

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++;
}

Comments

1

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.