Thursday, 18 July 2013

Bind data to dropdownlist in Asp.net

The rencent posts have given on populate dropdownlist with different source controls.Now i will showing a process which is not used any data source control or generic control.Here we need to create a connection string to data base in configuration file ,then it will be access to code behind file while require to DB connection.After that we can get the data from table using SqlDataAdapter and fill to connection less data set.Finally it has to be used as data source of dropdownlist
<html>
<head runat="server">
<title>Bind Data To DropdownList in asp.net</title>
</head>
<body>
<form id="dynamic" runat="server">
<div>
<asp:DropDownList ID="ddlcollege" runat="server">
</asp:DropDownList>
</div>
</form>
</body>
</html>
Connection String in Web.Config:
<add name="DbJConnectionString" connectionString="Data Source=jyothim\sqlexpress;Initial Catalog=TestDb;Integrated Security=True"
   providerName="System.Data.SqlClient" />
Code behind:
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;

public partial class PopulateDropdownListDB : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
PopulateDropdownDynamicallyfromDataBase();
}
}
private void PopulateDropdownDynamicallyfromDataBase()
{
try
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["DBjConnectionString"].ToString());
SqlDataAdapter ad = new SqlDataAdapter("select *from CollegeName", con);
DataSet ds = new DataSet();
ad.Fill(ds, "College");
ddlcollege.DataSource = ds;
ddlcollege.DataTextField = "college_name";
ddlcollege.DataBind();
}
catch (SqlException ex)
{
Response.Write(ex.Message.ToString());
}
}
}

No comments:

Post a Comment