2015-01-14 54 views
0

我有一個下拉列表(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"; 
+0

你的問題是什麼?什麼是錯誤? 想想那個,我想你可能會自己動手...... – Xeun

回答

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

我打敗了你;)感謝你的迴應。 – SearchForKnowledge

+1

@SearchForKnowledge:是啊!偉大的發現你自己的答案。做得好!!! –

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

我也用這個作爲一個解決方案:

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++; 
} 
1
var strSpecArrayForTopics = Specialty.Items.Cast<ListItem>().Select(x => x.Value).ToArray(); 
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(); 
+0

這絕對是一個很好的解決方案。謝謝。 +1 – SearchForKnowledge

相關問題