如何限制列表框中添加的项目数

时间:2018-02-23 07:23:07

标签: c#

我正在尝试创建一个按钮,将文本框Item1.Text的值添加到我的列表框中。如果项目数达到3,则用户将无法再添加。但是,我的代码在第一次尝试时不会在文本框中添加单个项目。

       for (int i = 0; i<=3 && i < listBox1.Items.Count; i++)
            {
                listBox1.Items.Add(Item1.Text);
                Item1.Focus();
                Item1.Text = String.Empty;
            }
          messagebox.Show("You've reached the number of items")

2 个答案:

答案 0 :(得分:4)

如果我理解你的问题:

if( listBox1.Items.Count <= 3 ){
    listBox1.Items.Add(Item1.Text);
    Item1.Focus();
    Item1.Text = String.Empty;
}else{
    messagebox.Show("You've reached the number of items")
}

答案 1 :(得分:2)

i < listBox1.Items.Count;你的循环条件不会第一次传递,因为i==0listbox1.items.count也是0,因为它是空的。

if(listBox1.Items.Count <= 3)
{
    listBox1.Items.Add(Item1.Text);
    Item1.Focus();
    Item1.Text = String.Empty;
} 
else
    messagebox.Show("You've reached the number of items")
相关问题