簡體   English   中英

無法使用ListBox項目填充數組

[英]Can't populate array with ListBox items

這是我想在網絡表單中使用的Windows表單:

// Assign the people to groups.
private void btnAssign_Click(object sender, EventArgs e)
{
    // Get the names into an array.
    int numPeople = lstPeople.Items.Count;
    string[] names = new string[numPeople];
    lstPeople.Items.CopyTo(names, 0);

    // Randomize.
    Randomizer.Randomize<string>(names);

    // Divide the names into groups.
    int numGroups = int.Parse(txtNumGroups.Text);
    lstResult.Items.Clear();
    int groupNum = 0;
    for (int i = 0; i < numPeople; i++)
    {
        lstResult.Items.Add(groupNum.ToString() +
            "    " + names[i]);
        groupNum = ++groupNum % numGroups;
    }
}

但是ListBox Asp.Net ListBox與WinForms ListBox不同,因此該行帶有:

lstPeople.Items.CopyTo(names, 0);

引發以下錯誤:

無法將源數組中的至少一個元素轉換為目標數組類型。

我嘗試了很多,但找不到解決方法。 請幫忙。

在WebForms中, ListBox包含ListItem類型的項目,因此首先應以不同的方式聲明數組:

ListItem[] names = new ListItem[numPeople];
lstPeople.Items.CopyTo(names, 0);

另請注意, names[i]不再是字符串。 確定您要使用文本還是值,並進行適當的更改。 例如, Text (通過您可能想要使用string.Format的方式,請在此處設置string.Format ):

 lstResult.Items.Add(groupNum.ToString() + "    " + names[i].Text);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM