How to count ListBox list items in asp.net c#

Count ListBox Items
The following asp.net c# example code demonstrate us how can we count ListBox items programmatically at run time in c# script section. ListBox is an asp.net list web server control. ListBox can be empty or it can contain one or more ListItem objects.

We can populate a ListBox control statically by placing items between tags or we can populate it programmatically by adding item to ListBox control's items collection. Even we can populate ListBox items from various data source objects such as Array, ArrayList, Generic List, SqlDataSource etc.

So sometimes we need to count ListBox items programmatically. Collection<T> Class 'Count' property allow us to count the items (elements) of a collection. By using this Count property we can easily get the total number of elements in a ListBox control. Simply we can access the Count property as ListBixID.Items.Count. Count property count the items from a ListBox control and return an integer value.
ListBoxItemCount.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        int totalItems = ListBox1.Items.Count;
        Label1.Text ="ListBox Total Items: " + totalItems.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to get total number of items in ListBox (count items)</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy">asp.net ListBox Example: Count Items</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             ForeColor="SaddleBrown"
             Font-Size="Large"
             >
        </asp:Label>
        <br /><br />
        <asp:Label 
             ID="Label2" 
             runat="server"
             Text="asp.net Controls"
             Font-Bold="true"
             ForeColor="Salmon"
             >
        </asp:Label>
        <br />
        <asp:ListBox 
             ID="ListBox1"
             runat="server"
             AutoPostBack="false"
             >
             <asp:ListItem>HiddenField</asp:ListItem>
             <asp:ListItem>ImageMap</asp:ListItem>
             <asp:ListItem>ListBox</asp:ListItem>
             <asp:ListItem>Literal</asp:ListItem>
        </asp:ListBox>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server"
             Text="Count List Items"
             Font-Bold="true"
             ForeColor="Salmon"
             OnClick="Button1_Click"
             />
    </div>
    </form>
</body>
</html>
More asp.net examples