Bind Database Table to Dropdownlist in Asp.Net

Leave a Comment
In this article, we have learn how to manually bind database table to asp.net dropdownlist control.

To Start, First we have create database table called Category look like below :

database table

Now, First create web application called DropDownlistDemo and add web form called Default.aspx and add below code.

<form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>
    </div>
    </form>


In above code we have add one dropdowndownlist control to web form.

Now, add below code to the Default.aspx.cs page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Category"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            BindDropDownList();
        }
    }
    private void BindDropDownList()
    {
        SqlDataAdapter adp = new SqlDataAdapter("Select * from Category", con);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        DropDownList1.DataSource = ds;
        DropDownList1.DataTextField = "category_name";
        DropDownList1.DataValueField = "category_name";
        DropDownList1.DataBind();
    }
}

web.config

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <connectionStrings>
    <add name="Category" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=E:\Demo\DropDownListDemo\App_Data\Database.mdf;Integrated Security=True;User Instance=True"
        providerName="System.Data.SqlClient" />
  </connectionStrings>
  <system.web>
        <compilation debug="false" targetFramework="4.0" />
    </system.web>
</configuration>


Demo



0 comments:

Post a Comment