Adyt
Adyt

Reputation: 1472

listbox validation

how do i check if an item is selected or not in my listbox? so i have a button remove, but i only want that button to execute if an item is selected in the list box. im using asp.net code behind C#. I'd prefer if this validation occurred on the server side.

cheers..

Upvotes: 0

Views: 5653

Answers (6)

Sani Huttunen
Sani Huttunen

Reputation: 24395

To remove multiple items you'll need to parse the items in reverse.

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

If you parse as usual then the result will be quite unexpected. Ex: If you remove item 0 then item 1 becomes the new item 0. If you now try to remove what you believe is item 1, you'll actually remove what you see as item 2.

Upvotes: 1

Adyt
Adyt

Reputation: 1472

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

this is what i came up with.

Upvotes: -1

Joacim Andersson
Joacim Andersson

Reputation: 381

To remove an item from a collection you need to loop backwards.

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

Upvotes: 0

Gishu
Gishu

Reputation: 136683

You may want to go with the early-break out approach based on your prob desc & the fact that ListBox.SelectedIndex will return -1 if nothing is selected.

so to borrow some of tvanfosson's button 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 
}

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532745

On the callback for the button click, just check if the selected index of the list box is greater than or equal to zero.

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

Upvotes: 1

jons911
jons911

Reputation: 1836

Actually, SelectedIndex is zero-based, so your check has to be:

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

Upvotes: 1

Related Questions