Monday, April 7, 2014

Simple way to fetch data from database into dropdownlist Asp.NET

First Create a Table 


Then Save it.
Then add data into table


Drag dropdownlist control from toolbox in default.aspx file :-


<asp:DropDownList ID="DropDownList1" runat="server">
        </asp:DropDownList>

Now write the following code in Default.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;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection cn;
    SqlCommand cmd;
    SqlDataAdapter da;

    protected void Page_Load(object sender, EventArgs e)
    {
        cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\C#\WebSites\DropDownList DataBase 4\App_Data\Database.mdf;Integrated Security=True;User Instance=True");

        cmd = new SqlCommand("Select * from Mahi", cn);

        da = new SqlDataAdapter(cmd);

        DataSet ds = new DataSet();
        da.Fill(ds);

        DropDownList1.DataSource = ds;
        DropDownList1.DataTextField = "Name";
        DropDownList1.DataValueField = "ID";
        DropDownList1.DataBind();
    }
}

No comments:

Post a Comment