asp.net listbox.items.contains
The following asp.net c# example code demonstrate us how can we determine whether a ListItem object
contains in the ListBox items collection.
Collection<T> Class Contains() method determines whether an element is in the collection. So we can search for the specified ListItem object from ListBox list items collection by using Contains() method. Contains() method return a Boolean value. It returns True if the specified object is found; otherwise the method return False. Contains() method implements as ICollection<T>.Contains(T).
Collection<T> Class Contains() method determines whether an element is in the collection. So we can search for the specified ListItem object from ListBox list items collection by using Contains() method. Contains() method return a Boolean value. It returns True if the specified object is found; otherwise the method return False. Contains() method implements as ICollection<T>.Contains(T).
listbox-items-contains.aspx
<%@ Page Language="C#" AutoEventWireup="true"%>
<!DOCTYPE html>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
string[] birds = {
"Golden Oriole",
"Yellow Oriole",
"Orchard Oriole",
"Northern Oriole",
"Cowbird",
"African Black-headed Oriole"
};
ListBox1.DataSource = birds;
ListBox1.DataBind();
ListBox1.Rows = ListBox1.Items.Count;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ListItem litem = new ListItem("Cowbird","Cowbird");
if (ListBox1.Items.Contains(litem))
{
Label1.Text = "item found: " + litem.Text + " | " + litem.Value;
}
else
{
Label1.Text = "not found";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>asp.net listbox.items.contains</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:MidnightBlue; font-style:italic;">
asp.net example - listbox.items.contains
</h2>
<hr width="550" align="left" color="Gainsboro" />
<asp:Label
ID="Label1"
runat="server"
Text="select item(s) from listbox."
Font-Size="X-Large"
Width="350"
>
</asp:Label>
<br /><br />
<asp:ListBox
ID="ListBox1"
runat="server"
AutoPostBack="true"
Font-Size="X-Large"
SelectionMode="Multiple"
Font-Names="Comic Sans MS"
>
</asp:ListBox>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
Text="ListBox Contains Item 'Cowbird'?"
OnClick="Button1_Click"
Height="40"
Font-Bold="true"
/>
</div>
</form>
</body>
</html>


- How to add attributes to DropDownList items
- How to sort DropDownList items in descending order
- How to sort ListBox items
- How to sort ListBox items alphabetically
- How to sort ListBox items by value
- How to display different tooltip on ListBox items
- How to set default selected items in a ListBox
- How to disable specific items in a ListBox
- How to add attributes to a ListBox items
- How to add vertical space between items in a RadioButtonList