Bind or Fill Dropdown list from Database in ASP.Net using C#
I.Introduction :
here i will explain how to fill or bind data in dropdownlist from the database .
II.Description:
Now create table
create table SecurityQuestion
(
SecurityQuestionId int primary key identity,
SecurityQuestion varchar(100)
)
Once the table design is complete insert the value and display the details
Once we finish creation of table in database now open your aspx page and write the code like as shown below
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title> how to bind data to dropdown from database </title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Select Secret Question :"></asp:Label>
<asp:DropDownList ID="drlquestion" runat="server"></asp:DropDownList><br />
</div>
</form>
</body>
</html>
After completion of aspx page add following namespaces in codebehind
web.config:
<connectionStrings>
<add name="Data" connectionString=Data Source=ZAFFER-BAIG\SQLEXPRESS;Initial Catalog=PUTraining;Integrated Security=True providerName="System.Data.SqlClient"/>
</connectionStrings>C# code
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
After completion of adding namespaces you need to write the code like as shown below
string strCon = ConfigurationManager.ConnectionStrings["Data"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind();
}
}
public void Bind()
{
using (SqlConnection con = new SqlConnection(strCon))
{
con.Open();
string sql = "select SecurityQuestion from PmsSecurityQuestion";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader dr = cmd.ExecuteReader();
drlquestion.Items.Insert(0, new ListItem("Select"));
int i = 1;
while (dr.Read())
{
drlquestion.Items.Insert(i, new ListItem(dr[0].ToString()));
i++;
}
}
}
Demo:
Hope you all understand the how to bind or fill data in dropdown list from database ..
Do have any query regarding my code you can comment below !!!
No comments:
Post a Comment