Insert database items to dropdown list in Asp.Net using C# coding
Database:
Inserted few records in the table.
Source code:
<%@ Page Language="C#"
AutoEventWireup="true" CodeBehind="ddl.aspx.cs"
Inherits="rememberme.ddl" %>
<!DOCTYPE html>
<html
xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DdlDepart"
runat="server"
CssClass="form-control">
</asp:DropDownList>
</div>
</form>
</body>
</html>
C# Code:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace rememberme
{
public
partial class ddl : System.Web.UI.Page
{
string constr =
ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection(constr))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from dept", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
DdlDepart.DataSource = ds;
DdlDepart.DataTextField = "dept";
DdlDepart.DataValueField = "id";
DdlDepart.DataBind();
DdlDepart.Items.Insert(0, new ListItem("--Select--",
"0"));
}
}
}
}
Output:
Figure:Select dropdown it will show dropdownlist which is added in database.
Thanks for visiting...