Working at Server-side
Using the server-side API, you can programmatically find, add, remove, disable, or select items in RadListBox.
Adding items
Use the Add method of the RadListBoxItemCollection object to add items programmatically:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
RadListBoxItem item = new RadListBoxItem("Item 1", "1");
RadListBox1.Items.Add(item);
//copy the first item
RadListBoxItem item2 = item.Clone();
RadListBox1.Items.Add(item2);
//make the third item disabled
RadListBoxItem item3 = new RadListBoxItem();
item3.Text = "Item 3";
item3.Value = "3";
item3.Enabled = false;
RadListBox1.Items.Add(item3);
}
}
Removing items
Use the Remove method of the RadListBoxItemCollection object to remove items:
RadListBoxItem itemToRemove = RadListBox1.FindItemByText("Item 3");
RadListBox1.Items.Remove(itemToRemove);
Sorting items
Use the SortItems method of RadListBox object to sort items:
RadListBox1.Sort = RadListBoxSort.Ascending;
RadListBox1.SortItems();
You can also use the Sort method of the RadListBoxItemCollection object to sort items:
RadListBox1.Items.Sort();
You can pass an object of type IComparer as an argument of the function:
protected void Button1_Click(object sender, EventArgs e)
{
RadListBox1.Items.Sort(new CustomComparer());
}
public class CustomComparer : System.Collections.IComparer
{
public CustomComparer() { }
public int Compare(object x, object y)
{
RadListBoxItem ItemX = (RadListBoxItem)x;
RadListBoxItem ItemY = (RadListBoxItem)y;
return ItemX.Text.CompareTo(ItemY.Text);
}
}
You can also use a lambda expression as an argument:
RadListBox1.Items.Sort(item => item.Text);
Disabling items
Use the Enable property of the RadListBoxItem object to enable or disable an item:
RadListBoxItem itemToDisable = RadListBox1.FindItemByText("Item 3");
itemToDisable.Enabled = false;
RadListBox1.Items[0].Enabled = false;
Selecting items
Use the Selected property of an item to select it, or use the SelectedIndex property of RadListBox. Note that to select multiple items you need to set the SelectionMode="Multiple" property.
RadListBoxItem itemToSelect = RadListBox1.FindItemByText("Item 3");
itemToSelect.Selected = true;
RadListBox1.Items[0].Selected = true;
Finding items
You can locate an item by searching on the Text or Value properties. You can retrieve either the index of the item or a reference to the item itself. Use the following RadListBox methods:
-
FindItemByText
-
FindItemByValue
-
FindItemIndexByValue
Collections of items
You can use the following collections of RadListBoxItem objects:
-
Items - retrieves a list of all items
-
SelectedItems - retrieves a list of all selected items
-
CheckedItems - retrieves a list of all checked items (when the CheckBoxes property is True)