如何将列表框的 rows/indexes 限制为指定的数字?

How do I limit the rows/indexes of a Listbox to a specified number?

如何以编程方式将列表框中 rows/indexes 的数量从动态数量限制为恒定数量,例如 5?例如,用户将数据从文本框输入到列表框,直到第五行。如果他们再次尝试,程序将拒绝用户输入的数据,这将阻止列表框增加动态行大小。

我尝试使用 Selected Index 和 Selected Items 属性,例如:

if (ListBox1.SelectedItems.Count != 0)
{
    while (ListBox1.SelectedIndex == 5)
    {
        ListBox1.Items.RemoveAt(ListBox1.SelectedIndex);
    }
}

但似乎属性需要选择列表框索引。

if(ListBox1.Items.Count < 5){
     ListBox1.Items.Add("asd");
}

您可以在插入时检查 ListBox1 中的项目数是否小于 5,而不是删除,如果成立则只添加一个项目。