简体   繁体   中英

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

How do I restrict the amount of rows/indexes in a list box from a dynamic amount to a constant amount, like 5, programmatically? For example, a user inputs data from a text box to a list box up to the fifth row. If they attempt again, the program would reject the data the user entered which would prevent the list box from increasing the dynamic row size.

I tried using Selected Index and Selected Items properties such as:

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

but it seems that the properties require a list box index to be selected.

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

Instead of removing, while inserting, you can check if the number of items in ListBox1 are less than 5 and only add an item if it holds true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM