Bind ListBox With SQL Database In ASP.NET Web Forms | ASP.NET

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


<!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" SelectionMode="Multiple" Font-Bold="true" Font-Italic="true" Font-Size="Large" ForeColor="#CC3399">

                <%--<asp:ListItem Value="1" Text="India"></asp:ListItem>

                <asp:ListItem Value="2" Text="SriLanka"></asp:ListItem>

                <asp:ListItem Value="3" Text="USA"></asp:ListItem>

                <asp:ListItem Value="4" Text="South Africa"></asp:ListItem>

                <asp:ListItem Value="5" Text="England"></asp:ListItem>

                <asp:ListItem Value="6" Text="Canada"></asp:ListItem>--%>

            </asp:ListBox>

            <br />

            <br />

            <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click"/>

        </div>

    </form>

</body>

</html>

Above File is ListBoxAsp\WebForm1.aspx
















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

namespace ListBoxAsp
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindListBox();
            }
        }

        void BindListBox()
        {
            try
            {
                using(SqlConnection con = new SqlConnection(cs))
                {
                    con.Open();
                    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();
                }
            }
            catch (SqlException ex)
            {
                Response.Write("SqlException: " + ex.Message);
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.Message);
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                if (ListBox1.SelectedIndex == -1)
                {
                    Response.Write("Please select any country..");
                }
                else
                {
                    foreach (ListItem li in ListBox1.Items)
                    {
                        if (li.Selected)
                        {
                            Response.Write("Selected Item Text is : " + li.Text + "<br>");
                            Response.Write("Selected Item Value is : " + li.Value + "<br>");
                            Response.Write("Selected Item Index is : " + ListBox1.Items.IndexOf(li) + "<br>");
                            Response.Write("------------------------------------------------------------------<br>");

                            //Response.Write("Selected Item Text is : " + ListBox1.SelectedItem.Text + "<br>");
                            //Response.Write("Selected Item Value is : " + ListBox1.SelectedItem.Value + "<br>");
                            //Response.Write("Selected Item Index is : " + ListBox1.SelectedIndex + "<br>");
                        }
                    }
                }
            }
            catch (SqlException ex)
            {
                Response.Write("SqlException: " + ex.Message);
            }
            catch (Exception ex)
            {
                Response.Write("Exception: " + ex.Message);
            }
        }
    }
}
Above File is ListBoxAsp\WebForm1.aspx.cs
















<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  https://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.7.2" />
    <httpRuntime targetFramework="4.7.2" />
    <pages>
      <namespaces>
        <add namespace="System.Web.Optimization" />
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
      </controls>
    </pages>
  </system.web>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
        <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Web.Infrastructure" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-13.0.0.0" newVersion="13.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
    </compilers>
  </system.codedom>
<connectionStrings>
<add name="dbcs" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\DotNet\ListBoxAsp\ListBoxAsp\App_Data\MyEmployeeDB.mdf;Integrated Security=True" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Above File is Web.config


















CREATE TABLE [dbo].[employee]
(
[Id] INT NOT NULL PRIMARY KEY identity,
[name] VARCHAR(50) NOT NULL,
[gender] VARCHAR(50) NOT NULL,
[age] INT NOT NULL,
[salary] INT NOT NULL
)

INSERT INTO employee(name,gender,age,salary) VALUES('Arjun','Male',23,240000),
('Aman','Male',24,260000),
('Umesh','Male',22,210000),
('Rashmi','Female',26,290000),
('Uday','Male',21,200000),
('Naman','Male',25,340000),
('Yatrik','Male',27,350000),
('Ajay','Male',22,150000);








Comments

Popular posts from this blog

Range Validator Control In ASP.NET Web forms | Form Validation | ASP.NET Web forms

Query String In ASP.NET Web Forms | State Management | ASP.NET | Web Forms

Validation Summary Control In ASP.NET Web forms | Form Validation | ASP.NET