Follow us

Header Ads

Show Data in ListBox using Database in Asp.Net WebForm

 BindingListBoxWithDatabase.aspx

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
      <h1>Binding Listbox with Database</h1>

            <br />
            <asp:ListBox ID="ListBox1" runat="server"></asp:ListBox>
            <br />
            <br />
            <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />

        </div>
    </form>
</body>
</html>

 BindingListBoxWithDatabase.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

public partial class BindingListBoxWithDatabase : System.Web.UI.Page
{
    string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            BindListBox();
        }
        
    }
    void BindListBox()
    {
        SqlConnection con = new SqlConnection(cs);
        string query = "select * from employee";
        SqlDataAdapter sda = new SqlDataAdapter(query,con);
        DataTable data = new DataTable();
        sda.Fill(data);
        ListBox1.DataSource = data;
        ListBox1.DataTextField = "name";
        ListBox1.DataValueField = "id";
        ListBox1.DataBind();//It is use to bind listbox with database
    }

    protected void Button1_Click(object sender, EventArgs e)
    {

    }
}

Post a Comment

0 Comments