C# – How to limit maximum number of values (entries) in a listbox

asp.netcnet

I currently have two ListBoxes (ListBox1 and ListBox2) with 12 static values in ListBox1 (value1, value2, value3, etc.) that allows the user to transfer values between them using an add and remove button. I also have a drop down box. How do I enforce a max on ListBox2 when a certain selection is made on that drop down box? In other words, if I just wanted to allow a max of one entry from Listbox1 to be moved to Listbox2 when a value is selected in the drop down box.

 protected void MoveRight(object sender, EventArgs e)
{
    while (ListBox1.Items.Count > 0 && ListBox1.SelectedItem != null)
    {
        ListItem selectedItem = ListBox1.SelectedItem;
        selectedItem.Selected = false;
        ListBox2.Items.Add(selectedItem);
        ListBox1.Items.Remove(selectedItem);
    }
}
protected void MoveLeft(object sender, EventArgs e)
{
    while (ListBox2.Items.Count > 0 && ListBox2.SelectedItem != null)
    {
        ListItem selectedItem = ListBox2.SelectedItem;
        selectedItem.Selected = false;
        ListBox1.Items.Add(selectedItem);
        ListBox2.Items.Remove(selectedItem);
    }
}
private void BindData()
{
    ListBox1.Items.Add(new ListItem("01", "01"));
    ListBox1.Items.Add(new ListItem("02", "02"));
    ListBox1.Items.Add(new ListItem("03", "03"));
    ListBox1.Items.Add(new ListItem("04", "04"));
    ListBox1.Items.Add(new ListItem("05", "05"));
    ListBox1.Items.Add(new ListItem("06", "06"));
    ListBox1.Items.Add(new ListItem("07", "07"));
    ListBox1.Items.Add(new ListItem("08", "08"));
    ListBox1.Items.Add(new ListItem("09", "09"));
    ListBox1.Items.Add(new ListItem("10", "10"));
    ListBox1.Items.Add(new ListItem("11", "11"));
    ListBox1.Items.Add(new ListItem("12", "12"));

}

Best Answer

Use a for loop that iterates the lesser of your max and the number of items in the list.

protected void MoveRight(object sender, EventArgs e)
{
    int max = 1;
    int iterations = ListBox1.Items.Count < max ? ListBox1.Items.Count : max
    for(int i = 0; i < iterations; i++)
    {
        ListItem selectedItem = ListBox1.SelectedItem;
        if(selectedItem == null)
            break;

        selectedItem.Selected = false;
        ListBox2.Items.Add(selectedItem);
        ListBox1.Items.Remove(selectedItem);
    }
}

Now you can move max into the class definition and manipulate it however you need to.

Related Topic