Add ListItem to ListBox : ListBox « Asp Control « ASP.Net






Add ListItem to ListBox



<form runat="server">
<script language="C#" runat="server">
protected void Page_Load(object o, EventArgs e) {
    if(!IsPostBack) {
        ListItem item;
        item = new ListItem("A");
        languageListBox.Items.Add(item);
        item = new ListItem("B");
        languageListBox.Items.Add(item);
        item = new ListItem("C");
        languageListBox.Items.Add(item);
        languageListBox.Rows = 3;
    }
}

protected void ListBoxSelectionChanged(object o, EventArgs e) {
    bool valueSet = false;
    foreach(ListItem item in languageListBox.Items) {
        if (item.Selected) {
            if(valueSet) {
                favoriteLanguage.Text += ", " + item.Text;
            }
            else {
                favoriteLanguage.Text = item.Text;
                valueSet = true;
            }
        }
    }
}
</script>
<asp:ListBox 
    id="languageListBox"
    runat="server" 
    SelectionMode="multiple" 
    OnSelectedIndexChanged="ListBoxSelectionChanged" /><br />
    Favorite Language: 
    <b><asp:label runat="server" 
                  id="favoriteLanguage" 
                  style="color:blue" 
                  Text="Not Set" /></b><br />
<asp:button runat="server" Text="Submit"/>
</form>

 








Related examples in the same category

1.Set static value for asp:listbox (VB.net)
2.asp:listbox: On selected index changed
3.Get selected index, text and value from asp:listbox (VB.net)
4.Change background color for asp:listbox (VB.net)
5.Allowing Multiple Selections in a ListBox Control (VB.net)
6.Get selected index from asp:listbox (VB.net)
7.Get selected item from ListBox (C#)
8.Using the ListBox to select list items.