Populate ListBox from SqlDataSource in asp.net c#

Populate ListBox from SqlDataSource
ListBox is a Standard ToolBox Control. In this simple example here I show how to populate ListBox with SqlDataSource.

First create a WebForm name ListBoxSqlDataSource.aspx. Then add a SqlDataSource Control, a ListBox Control and a Label Control. I save a ConnectionString in web.config file and use it for SqlDataSource ConnectionString property. In this example I use the NorthWind database. Here is the source code of ListBoxSqlDataSource.aspx file.

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

<!DOCTYPE html>

<script runat="server">
    protected void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e) {
        Label1.Text ="You selected: " +
                    ListBox1.SelectedItem.Text.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ListBox Example: How to populate ListBox from SqlDataSource</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:SqlDataSource
             ID="SqlDataSource1"
             runat="server" 
             ConnectionString="<%$ ConnectionStrings:AppConnectionString %>" 
             SelectCommand="SELECT [ProductName] FROM [Products]"
             >
        </asp:SqlDataSource>
        <asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="BlueViolet"/>
        <br /><br />
        <asp:Label ID="Label2" runat="server" Text="Choose one"></asp:Label>
        <br />
        <asp:ListBox
             ID="ListBox1"
             runat="server"
             AutoPostBack="True" 
             OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"
             DataSourceID="SqlDataSource1"
             DataTextField="ProductName" 
             DataValueField="ProductName"
             >
        </asp:ListBox>
    
    </div>
    </form>
</body>
</html>
More asp.net examples