Skip to main content

How to populate dropdown using database using linq to Sql and Sql


Hello every one today I am going to show you how you can bind a drop down list using  database. As
The Dropdown List control also supports data binding. To bind the control to a data source below are main points that need to be consider

·         Create a data source that contains the items to display in the control.
·         Use the Data Text Field and Data Value Field properties to specify which field in the data source to bind to the Text and Value properties of each list item in the control, respectively.
·         Control.DataBind method to bind the data source to the Drop down List control.



Step 1
We will create a database you can use below script to generate a database table

CREATE TABLE [dbo].[EmpDemo](
      [EmpID] [int] IDENTITY(1,1) NOT NULL,
      [Emp_name] [nvarchar](50) NULL,
      [Emp_department] [nvarchar](50) NULL,
 CONSTRAINT [PK_EmpDemo] PRIMARY KEY CLUSTERED
(
      [EmpID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]


Step 2

Put drop down list on aspx page

  <asp:DropDownList ID="ddlemp" DataValueField="EmpID" DataTextField="Emp_name" runat="server"> </asp:DropDownList> 


Notice DataValueField and DataTextField 


Step 3
Below is code that needs to be write on code behind to get data from database



public void FillDropdownusingsql()
    {
        try
        {
            SqlConnection con = new SqlConnection(@"Your Connection string");

            con.Open();
            String getState = "Select * from EmpDemo";
            DataTable dt = new DataTable();
            SqlDataAdapter da = new SqlDataAdapter(getState, con);
             da.Fill(dt);
            ddlemp.DataSource = dt;

     // DataTextField and DataValueField can also be assigned from code behind

            //ddlemp.DataTextField = " Emp_name ";
            //ddlemp.DataValueField = " EmpID ";
            ddlemp.DataBind();

            con.Close();
        }

        catch (Exception eee)
        {
        }
    }



 Call this method on page load


 Blow is link from where you can download complete code of this demo this code include  linq approach and above approach this demo Download Code

Comments