将ListBox项存储在单独的变量中

时间:2017-03-28 19:18:15

标签: c#

我的ListBox控件中最多可以有四个项目。我想将显示的文本分配给字符串变量,但是一旦到达string Two,我就会遇到索引超出范围的问题。我知道为什么会这样(列表框中只有一个项目......)但我似乎无法理解如何做到这一点。

我可以构建某种if语句来处理这个问题,但我认为可能有一种更有效的方法,而不是检查它是否少于2项,超过1项等。

我的代码的简单版本:

public void button1_Click(object sender, EventArgs e)
{
    if (listBox1.Items.Count < 4) {
        listBox1.Items.Add(comboBox1.Text);
    } else {
        System.Windows.Forms.MessageBox.Show("Too many");
    }

    string One = listBox1.Items[0].ToString();
    string Two = listBox1.Items[1].ToString();
    string Three = listBox1.Items[2].ToString();
    string Four = listBox1.Items[3].ToString();
}

请注意,我不能使用数组,因为我需要访问另一个无法迭代数组或访问其索引的应用程序中的变量。

3 个答案:

答案 0 :(得分:1)

您可以创建一个临时数组来为您处理复制:

if (listBox1.Items.Count < 4) {
    listBox1.Items.Add(comboBox1.Text);
} else {
    System.Windows.Forms.MessageBox.Show("Too many");
}

string[] ListItemsArray= new string[4];
listBox1.Items.CopyTo(ListItemsArray, 0);

//Then you can leave this here:
string One   = ListItemsArray[0] ?? "";
string Two   = ListItemsArray[1] ?? "";
string Three = ListItemsArray[2] ?? "";
string Four  = ListItemsArray[3] ?? "";

解释了listBox1.Items.CopyTo()方法here

如果您不希望任何值为null,则使用??运算符

答案 1 :(得分:0)

如果它真的只有4个项目,那么手动敲掉它?

string One = "";
string Two = "";
string Three = "";
string Four = "";

if (listBox1.Items.Count >= 1)
{
    One = listBox1.Items[0];
}
if (listBox1.Items.Count >= 2)
{
    Two = listBox1.Items[1];
}
if (listBox1.Items.Count >= 3)
{
    Three = listBox1.Items[2];
}
if (listBox1.Items.Count >= 4)
{
    Four = listBox1.Items[3];
}

它不优雅,但工作已经完成。

答案 2 :(得分:0)

您可以在 listBox.Items 上使用 for 循环,这样您就不会尝试访问超出范围的索引。

您可以先创建一个字符串数组,如下所示:

string[] names = new string[] { "", "", "", "" };

然后你可以在列表框的项目上使用for循环,并将刚刚创建的字符串数组的字符串设置为等于listBox [index] .ToString()中的任何内容,如:

for (int i = 0; i < listBox.Items.Count; i++)
        {
            names[i] = listBox.Items[i].ToString();
        }

最后,使用:

设置原始变量
string one = names[0];
string two = names[1];
string three = names[2];
string four = names[3];

如果上面的任何字符串都是空字符串,则表示列表框中该位置没有任何项目,或者列表框中的项目实现ToString()以返回空字符串。

不确定我是否理解你的问题,但我会做那样的事情。

相关问题