Items.FindByValue("Record 1").Selected = true;
Removing List Items from the ListBox Control
You can remove a list item from the ListBox control using the RemoveAt() method
that accepts the index number of the list item that you need to remove from the
collection of list items.
ListBox1.Items.RemoveAt(0);
To remove all the list items from the ListBox control, use the following code:
ListBox1.Items.Clear();
Working with List Controls in ASP.NET
[ 40 ]
Binding Data to the ListBox Control
We have already discussed how we can bind static data to this control declaratively.
For programmatic data binding we can use the DataManager class that we designed
in Chapter 1. Note that we would use this class for programmatic data binding for
this and the other list controls that we would cover in this chapter.
To bind data to the ListBox control programmatically, we need to set the
DataTextField and the DataValueField properties appropriately and then make a
call to the DataBind() method shown as follows:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataManager dataManager = new DataManager();
listBox.DataSource = dataManager.GetDataFromArrayList();
listBox.DataValueField = "EmpCode";
listBox.DataTextField = "EmpName";
listBox.DataBind();
}
}
The DataTextField property is used to retrieve the contents of the Text property
of the control, whereas the DataValueField property is used to retrieve the
contents of the Value property of the control.
Pages:
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54