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