Tuesday 16 June 2015

How to bind DropdownList from database


Here I will explain how to bind DropdownList from database
and in previous I posted this articles
how to access asp.net website in LAN
how to create database from script file
paging in html table using javascript

If you want to bind DropdownList from database table then you write following code in your website.


First , Your .aspx page should be like this



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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title> How to bind DropdownList from database </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Select: <asp:DropDownList ID="ddlType" runat="server">
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

And your C# code behind like this



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection cn;
    DataTable dt;
    protected void Page_Load(object sender, EventArgs e)
    {
        cn = new SqlConnection(ConfigurationManager.ConnectionStrings["Conn"].ConnectionString);
        if (!IsPostBack)
        {
            BindDropdwnlist();
        }

    }
    public void BindDropdwnlist()
    {
        SqlCommand cmd = new SqlCommand("SELECT id,Name from tbl",cn);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        dt = new DataTable();
        da.Fill(dt);

        ddlType.DataSource = dt;
        ddlType.DataTextField = "Name";
        ddlType.DataValueField = "Id";
        ddlType.DataBind();
    }
}

No comments:

Post a Comment



Asp.net tutorials