Bind DataSet to ListBox : ListBox « Data Binding « ASP.NET Tutorial






<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="DataSetBinding" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox ID="lstUser" runat="server" Height="152px" Width="192px"></asp:ListBox></div>
    </form>
</body>
</html>


File: Default.aspx.cs


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class DataSetBinding : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        DataSet dsInternal = new DataSet();
        dsInternal.Tables.Add("Users");

        dsInternal.Tables["Users"].Columns.Add("Name");
        dsInternal.Tables["Users"].Columns.Add("Country");

        DataRow rowNew = dsInternal.Tables["Users"].NewRow();
        rowNew["Name"] = "A";
        rowNew["Country"] = "USA";
        dsInternal.Tables["Users"].Rows.Add(rowNew);

        rowNew = dsInternal.Tables["Users"].NewRow();
        rowNew["Name"] = "B";
        rowNew["Country"] = "Canada";
        dsInternal.Tables["Users"].Rows.Add(rowNew);

        rowNew = dsInternal.Tables["Users"].NewRow();
        rowNew["Name"] = "C";
        rowNew["Country"] = "Japan";
        dsInternal.Tables["Users"].Rows.Add(rowNew);

        lstUser.DataSource = dsInternal.Tables["Users"];
        lstUser.DataTextField = "Name";

        lstUser.DataSource = dsInternal;
        lstUser.DataMember = "Users";
        lstUser.DataTextField = "Name";

        this.DataBind();

    }
}








19.20.ListBox
19.20.1.Bind DataSet to ListBox
19.20.2.Show list items with programmatic binding.
19.20.3.ListBox Control data binding with asp:SqlDataSource
19.20.4.Selecting multiple list items (set SelectionMode to Multiple)