views:

1122

answers:

7

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..

+1  A: 

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 );
    }
}
tvanfosson
Corrected with @jons911 observation.
tvanfosson
+1  A: 

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

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

jons911
A: 

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 
}
Gishu
A: 

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.

Adit
A: 

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
}
Joacim Andersson
A: 

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 know try to remove what you believe is item 1, you'll actually remove what you see as item 2.

Sani Huttunen
A: 

Better approach, don't let the button be clicked.

http://www.briankeating.net/blog/post/WPF-Datatriggers.aspx

JIm