How to populate dropdownlist with “Select” option in asp.net?



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");
}
}
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: