Now I would like to create a dynamic dropdownlist in ASP.Net using C#. I have a dropdownlist and I want to display items in it by binding
data from database into it on page load. My database is designed in MS SQL Server
2008, I have a table ( tblcountry ) and I want to get data from column
"country" to display as items of dropdownlist in ASP.Net.
// connect to database
//fill data into datatable
Sample table |
Code design:
<asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList>
Code Behind :
Import two namespaces
//import these two namespaces: System.Data and System.Data.SqlClient to use .NET
//Framework Data Provider for SQL Server
using System.Data;
using System.Data.SqlClient;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
DataTable dt = new DataTable();
dt = Loadlist();
DropDownList1.DataSource = dt;
DropDownList1.DataValueField = "country";
//country is table field name in tblcountry
//country is table field name in tblcountry
DropDownList1.DataBind();
}
}
public DataTable Loadlist()
{
SqlConnection con = new SqlConnection();
string str;
string sql;
str="Server=UBEE_THAROTH ; Database=Drink;uid=sa;pwd=123;";
sql = "Select * from tblcountry order by country asc";
// connect to database
con.ConnectionString = str;
con.Open();
//fill data into datatable
SqlDataAdapter da = new SqlDataAdapter(sql,con);
DataTable dt = new DataTable();
da.Fill(dt);
if(dt.Rows.Count>0){
return dt;
}
else {
return null;
}
}
Done …..enjoy with it :) :)
Binding data into dropdownlist in ASP.Net using C#
Reviewed by BeiLover
on
7:41 PM
Rating:
great
ReplyDeleteReally great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries. I want to say thanks for great sharing.
ReplyDeleteData Science Training in Indira nagar
Data Science training in marathahalli
Data Science Interview questions and answers
Data Science training in btm layout
Data Science Training in BTM Layout
Data science training in kalyan nagar
Data science training in bangalore