如何从下拉列表向字符串数组添加项目

时间:2015-01-14 14:47:33

标签: c# arrays

我有一个下拉列表(specialty),我想循环浏览专业中的选项数量并添加一个数组:

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

所以,让我们说专业下拉列表包含:

All
Card
Intern
Rad

数组应为:

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

5 个答案:

答案 0 :(得分:1)

您正在寻找for循环。

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

答案 1 :(得分:1)

我也用它作为解决方案:

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

答案 2 :(得分:1)

您需要为数组添加索引。检查以下代码:

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

答案 3 :(得分:1)

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

答案 4 :(得分:1)

您也可以使用LINQ。

using System.Linq;

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

如果.Value的类型为object,请使用以下内容。

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