Checking the list

how to check if an item is selected in my list? so I have a delete button, but I want this button to only execute if an item is selected in the list. im using asp.net code behind c #. I would prefer this check to be done server side.

amuses ..

0


source to share


6 answers


for (int i = 0; i < lbSrc.Items.Count; i++)
{
    if (lbSrc.Items[i].Selected == true)
    {
        lbSrc.Items.RemoveAt(lbSrc.SelectedIndex);
    }
}

      



here's what i came up with.

-1


source


In the callback, click the button, just check if the selected index in the list box is greater or equal to zero.



protected void removeButton_Click( object sender, EventArgs e )
{
    if (listBox.SelectedIndex >= 0)
    {
        listBox.Items.RemoveAt( listBox.SelectedIndex );
    }
}

      

+1


source


Actually the SelectedIndex is zero based, so your check should be:

if (listBox.SelectedIndex> = 0) ...

+1


source


To remove multiple elements, you need to parse the elements in reverse order.

protected void removeButton_Click(object sender, EventArgs e)
{
    for (int i = listBox.Items.Count - 1; i >= 0; i--)
        listBox.Items.RemoveAt(i);
}

      

If you disassemble it as usual, the result will be quite unexpected. Example: If you delete item 0, then item 1 becomes the new item 0. If you now try to delete what you think is item 1, you are effectively deleting what you see as item 2.

+1


source


You might want to go with an early breakout based on your problem and that ListBox.SelectedIndex will return -1 if nothing is selected .

to borrow some tvanfosson event handler code.

protected void removeButton_Click( object sender, EventArgs e )
{
    if (listBox.SelectedIndex < 0) { return; }
    // do whatever you wish to here to remove the list item 
}

      

0


source


To remove an item from the collection, you need to loop back.

for (int i=lbSrc.Items.Count - 1, i>=0, i--)
{
   //code to check the selected state and remove the item
}

      

0


source







All Articles