Hi
One of my friend asked with me “How to populate dropdownlist with “Select” option?” in asp.net. We can do this task like this
step1: Take one dropdownlist in .aspx page.
Step2:Write this code in code behind page 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.SqlClient;
using System.Data;public partial class DdlTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindDropdown();
}}
protected void bindDropdown()
{
using (SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True"))
{
//change the sqlquery into store procedure for better performance
using (SqlCommand cmd = new SqlCommand("Select top 10 Id,EmpName from tblEmp", con))
{
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
DropDownList1.DataSource = dt;
DropDownList1.DataTextField ="EmpName";
DropDownList1.DataValueField = "Id";
DropDownList1.DataBind();// what ever you want to display on top of dropdown keep here
// DropDownList1.Items.Insert(0, new ListItem(“Select”, “0”));DropDownList1.Items.Insert(0, "Select");
}
}
}
}