listbox to listbox
1. ListBox to ListBox
2. listbox multiple selection:
3. Listbox ClearSelection
4. Clear Listbox
ListBox is a collection of list items where each list item is a pair of Text and Value.
1. ListBox to ListBox
To copy the selected items from source to destination refer below code
protected void Button1_Click(object sender, EventArgs e)
{
for( int i=0; i<lstSource.Items.Count; i++ )
{
if (lstSource.Items[i].Selected)
{
lstDestination.Items.Add( lstSource.Items[i] );
Response.Write("Item Text " + lstSource.Items[i].Text + " & Value " + lstSource.Items[i].Value + " Added to Destination </br> ");
}
}
}
Description: The for loop iterates the list and if it selected item found it copies it to destination listbox.
| Code |
Description |
| lstSource.Items[i] |
Selected Check whether item in listbox is selected or not |
| lstSource.Items[i] |
Returns ListItem |
| lstDestination.Items.Add ( ListItem instance ) |
appends listitem in destination listbox. The add method accepts ListItem as a
parameter. |
Error: Cannot have multiple items selected when the SelectionMode is Single:
Description: Make sure that destination listbox has Selection Mode property set to Multiple.
2. listbox multiple selection:
To allow listbox multiple selection, set selectionMode property of that control to Multiple as shown in below fig.
Code
protected void Button1_Click(object sender, EventArgs e)
{
foreach (ListItem li in ListBox1.Items)
{
if (li.Selected)
{
Response.Write(li.Text + " " + li.Value + "</br>");
}
}
}
Output:
Three 3
Four 4
Single Select Allows user to choose only one item in the list while Multiple Select allows user to choose
zero or many or all items in the list box.
Clear ListBox
Clear method: Removes all items in ListBox.
ClearSelection: Clears selected Item.
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.ClearSelection();
ListBox1.Items.Clear();
}
Remove Selected Items from ListBox
protected void Button1_Click(object sender, EventArgs e)
{
foreach (ListItem li in ListBox1.Items)
{
if (li.Selected)
{
ListBox1.Items.Remove(li);
ListBox1.Items.Remove(li.Text);
Response.Write("Removed: " + li.Text + " " + li.Value + "</br>");
}
}
}
Be the first to rate this post
- Currently 0/5 Stars.
- 1
- 2
- 3
- 4
- 5