How to display data in listbox from SQL database in C#

In this article, we will learn How to display data in Listbox from the SQL database in C#.
Share it:

How to display data in Listbox from SQL database in C#

How to display data in listbox from SQL database in C#

In this article, we will learn How to display data in Listbox from the SQL database in C#.

how to display data in Listbox using c#


How to bind listview to database

ListBox control allows single or multiple item selection. To enable multiple item selection, set the SelectionMode property to Multiple.

Design View 


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="index.aspx.cs" Inherits="ListBox_data.index" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
        </div>
    </form>
</body>
</html>

Adding The Name Space

using System.Data;
using System.IO;
using System.Data.SqlClient;
Source Code
namespace ListBox_data
{
    public partial class index : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindCountryListBox();
            }
        }

        private void BindCountryListBox()
        {
            SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=TestDb1;Integrated Security=True;");
            SqlDataAdapter da = new SqlDataAdapter("select Name from stud", conn);
            DataSet ds = new DataSet();
            da.Fill(ds);
            ListBox1.DataSource = ds;
            ListBox1.DataValueField = "Name";
          
            ListBox1.DataBind();
        }
    }
}
Create Database:- SQL Command
CREATE TABLE [dbo].[stud] (
    [Id]      INT          NOT NULL,
    [Name]    VARCHAR (50) NULL,
    [Country] VARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);
Video

Share it:

aspnet

How to display data in Listbox from SQL database in C#

Post A Comment:

0 comments: