[英]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: 我有一个下拉列表(
specialty
),我想遍历special中的选项数量并添加一个数组:
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";
You are looking for a for
loop. 您正在寻找
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;
}
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++;
}
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;
}
var strSpecArrayForTopics = Specialty.Items.Cast<ListItem>().Select(x => x.Value).ToArray();
You can also use LINQ for this. 您也可以为此使用LINQ。
using System.Linq;
string[] strSpecArrayForTopics = Specialty.Items.Select(v => v.Value).ToArray();
if .Value
is of type object
, use the following. 如果
.Value
是object
类型,请使用以下内容。
string[] strSpecArrayForTopics = Specialty.Items.Select(v => (string)v.Value).ToArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.