Click here to Skip to main content
15,901,666 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi,

Can anyone know?

what is the syntax for delete an item in listbox?
Posted

Dear Friend,

I am giving you the solution to delete one or more than one item.

For multiple selection of Items, you need to set the .SelectionMode property:

listBox1.SelectionMode = SelectionMode.MultiExtended;

Next, I am assuming that you have added the Items to your ListBox programmatically rather than using a DataSource (you wouldn't be able to remove them from the Items collection directly if the ListBox is using a DataSource).

It is done n the reverse order just in order to complete the operation of deletion successfuly
.

All you need to do is use the .RemoveAt() method, in reverse order (it is important to do it backwards, otherwise they won't be removed properly):-
for (int i = listBox1.SelectedIndices.Count-1; i >= 0; i--)
{
 listBox1.Items.RemoveAt(listBox1.SelectedIndices[i]);
}

OR
for (int i = 0; i < listBox1.SelectedItems.Count; i++)
      {
        listBox1.Items.Remove(listBox1.SelectedItems[i].ToString());
        i--;
      }
 
Share this answer
 
v2
C#
ListBox1.Items.Remove(ListBox1.SelectedItem);
 
Share this answer
 
Comments
Anuja Pawar Indore 20-Feb-12 2:28am    
Added pre tag
Hi,

C#
protected void remove_Click(object sender, EventArgs e)
    {
        if (ListBox1.SelectedItem.Text == null)
        {
            lblError.Text = "Please select an item for deletion.";
        }
        else
        {
            string remove = ListBox1.SelectedItem.Text;
            ListBox1.Items.Remove(remove);
        }
    }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900