Binding a ListControl with Values from the Database
The Concept
In ASP.Net, we have number of List Controls such as DropDownList, ListBox, CheckBoxLists, RadioButtonList and BulletedList which contains a list of items in key value pair. Sometimes, it is required to bind these types of controls with values from any Database table.
The following code exaplains how to bind a DropDownList with values from any Database table.
Code
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
DataTable dt = GetKeyValuePair("TblStudents", "sname", "sid", "-SELECT-");
DropDownList1.DataSource = dt;
DropDownList1.DataTextField = "sname";
DropDownList1.DataValueField = "sid";
DropDownList1.DataBind();
}
}
public DataTable GetKeyValuePair(string TableName, string KeyColumn, string ValueColumn, string DefaultValue)
{
string query;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["sqlcon"].ToString());
SqlDataAdapter sqlda;
DataTable dt;
query = "SELECT '" + DefaultValue + "' AS " + KeyColumn + " , '" + DefaultValue + "' AS " + ValueColumn + " FROM " + TableName + " UNION ";
query += "SELECT " + KeyColumn + ", " + ValueColumn + " FROM " + TableName;
sqlda = new SqlDataAdapter(query, con);
dt = new DataTable();
sqlda.Fill(dt);
return dt;
}
Code Explanation
In the above code, we have one method called GetKeyValuePair which takes 4 parameters:
For Example, you have a table named TblEmp with columns empid and empname. The method can be used as follows:
DataTable dt = GetKeyValuePair("TblEmp", "empname", "empid", "Please Select");
Thanks & Regards
Paritosh Mohapatra