How to bind drop down value from database in aspnet c#

In this article, I will show how to bind the drop down list in asp.net C#, in other word how to show database value in drop down list in asp.net c#, many times we need to show the database value in dropdown list according to id. So this post sure helps you
We need to create a database:-

Design:-





Script:-
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[record](
          [record_id] [int] IDENTITY(1,1) NOT NULL,
          [Name] [nvarchar](50) NULL,
          [Contact_no] [nvarchar](50) NULL,
          [Email] [nvarchar](50) NULL,
 CONSTRAINT [PK_record] PRIMARY KEY CLUSTERED
(
          [record_id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO


Source Code:-
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="dropdownlist.aspx.cs" Inherits="dropdownlist" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

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

   
    </div>
    </form>
</body>
</html>


Code behind(c#):-

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

public partial class dropdownlist : System.Web.UI.Page
{
   
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            dropboind();
        }
    }

    protected void dropboind()
    {

        SqlConnection con = new SqlConnection("Data Source=NEERAJ-PC;Initial Catalog=CodeSolution;Persist Security Info=True;User ID=sa; password=12345678");
        con.Open();
        SqlCommand cmd = new SqlCommand("Select * from record",con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);

        DataSet ds = new DataSet();
        da.Fill(ds);
      
        DropDownList1.DataTextField = ds.Tables[0].Columns["Name"].ToString();
        DropDownList1.DataValueField = ds.Tables[0].Columns["record_id"].ToString();

        DropDownList1.DataSource = ds.Tables[0];
        DropDownList1.DataBind();

        //Adding "Please Select" option in dropdownlist as a Frist Value or for Validation
      
        DropDownList1.Items.Insert(0, new ListItem("Please Select", "0"));
       
        //or
       
       
        //DropDownList1.Items.Insert(0, "Please Select");


    }
}

Out-put:-




How to bind drop down value from database in aspnet c# How to bind drop down value from database in aspnet c# Reviewed by NEERAJ SRIVASTAVA on 9:16:00 AM Rating: 5

No comments:

Powered by Blogger.