Binding Data to Dropdownlist from DataBase
---------------------------------------------------------------
Today Iam going to write on Binding Data to Dropdownlist from Database
Consider that we want to populate the Dropdownlist with a list of countries. For this first we need to create a new .aspx page with the following code
<asp:dropdownlist id =" “dpdcountry”" runat="”server”">
</dropdownlist>
Now create a new classlibrary with the class name DataBinding.cs and write the following code
public class Databinding
{
public static DataTable Execute(string sqlstring)
{
SqlConnection con = new SqlConnection(connectionstring);
DataTable dt = new DataTable(“tb1”);
try
{
con.Open();
SqlCommand cmd = new SqlCommand(sqlstring, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt) ;
}
catch(Exception e)
{
throw e;
}
finally
{
con.Close();
}
return dt;
}
}
In the above code Databinding is the class name, Execute is the method which returns a datatable. In the connectionstring you need to specify the 4 parameters of the SqlConnection string.
Now in the .aspx.cs file under Page_Load method you need to write the following the code
If(!IsPostBack)
{
string str = “select country_id , name from Country”;
Datatable dt = Databinding.Execute(str);
dpdcountry.DataValueField = dt.columns[0].ToString();
dpacountry.DataTextField = dt.cloumns[1].ToString();
dpdcountry.DataSource = dt;
dpdcountry.DataBind();
}
On a whole, first we declared a dropdownlist with the name dpdcountry in the .aspx page. Then in .aspx.cs page, in the Page_Load method we are sending the sql string to the class Databinding which connects to the database and returns the data table containg the country names. Then this data table is assigned to the dropdownlist as its datasource. So, when you run this code you get a page with the dropdownlist populated with country names.
Note:
1. You should add the Class Library name in the Referrences of the Project
2. You should use the Class Library name in the directories part of the .aspx.cs page