Thursday 2 January 2014

Bind / Fill dropdownlist using asp net from database

Posted on 04:53 in
Introduction:

This article is helps to how to bind dropdownlist values from database in datatable formats (methods 2) using asp.net.

Designing Page (Source Code):

<!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>Fill dropdownlist using asp net from database</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%--Method 1--%>
<asp:DropDownList ID="ddlDepartment" runat="server">
<asp:ListItem Text="Computer Science Engineering" Value="CSE"></asp:ListItem>
<asp:ListItem Text="Mechanical Engineering" Value="ME"></asp:ListItem>
<asp:ListItem Text="Civil Engineering" Value="CE"></asp:ListItem>
<asp:ListItem Text="Electrical and Electronics Engineering" Value="EEE"></asp:ListItem>
</asp:DropDownList>
<%--Method 2--%>
<asp:DropDownList ID="ddlDepartmet1" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
</html>
VB.NET:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim con As New SqlConnection("server=192.168.1.100;uid=sa;pwd=sa123;database=asp_dotnet")
            con.Open()
            Dim cmd As New SqlCommand("SELECT * FROM STUDENTDETAILS", con)
            Dim da As New SqlDataAdapter(cmd)
            Dim dt As New DataSet()
            da.Fill(dt)
            con.Close()

            ddlDepartmet1.DataSource = dt
            ddlDepartmet1.DataTextField = "department"
            ddlDepartmet1.DataValueField = "Id"
            ddlDepartmet1.DataBind()
            Dim SelectOption As New ListItem("- - Select - - ", "0")
            ddlDepartmet1.Items.Insert(0, SelectOption)
        End If
End Sub
C#.NET:
protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                SqlConnection con = new SqlConnection("server=192.168.1.100;uid=sa;pwd=sa123;database=asp_dotnet");
                con.Open();
                SqlCommand cmd = new SqlCommand("SELECT * FROM STUDENTDETAILS", con);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                con.Close();

                ddlDepartmet1.DataSource = dt;
                ddlDepartmet1.DataTextField = "department";
                ddlDepartmet1.DataValueField = "Id";
                ddlDepartmet1.DataBind();
                ListItem SelectOption = new ListItem("- - Select - - ", "0");
                ddlDepartmet1.Items.Insert(0, SelectOption);
            }

        }
Demo:

0 comments:

Post a Comment