This article will show you how you can bind a dropdownlist
in asp.net using c# by sql server from data table.
Some of my previous articles are as follows: Validation
of Duplicate Email Id Of Registration Form Using C# in Asp.Net, Insert,
Update, Delete Operation In Asp.Net MVC Using Entity Framework C#.Net ,CRUD
Functionality, Autocomplete
Textbox in Asp.Net With DataBase Using C# AjaxControlToolkit, Ajax
FileUpload Control In Asp.Net or Multiple FileUpload With Progress Example in
Asp.Net Using C#.Net, Bind
DropDownList Using Entity Framework in ASP.Net MVC Using C#.
So for this article first we will create a new sql table.
Now add some value in it.
Now we will create a new asp.net application and add the
below code into the .asp page.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2"
%>
<!DOCTYPE html
PUBLIC "-//W3C//DTD
XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Bind
DropdownList Using Sql Server and Datatable in Asp.Net and C#</title>
</head>
<body>
<form id="form1" runat="server">
<div>
Country Name :<asp:DropDownList ID="DropDownList1"
runat="server"
Width="150px">
</asp:DropDownList>
</div>
</form>
</body>
</html>
|
Now check the below code to bind the dropdown liat from the
database.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
namespace WebApplication1
{
public partial class WebForm2 : System.Web.UI.Page
{
protected
void Page_Load(object
sender, EventArgs e)
{
if
(!IsPostBack)
{
BindDdl();
}
}
private
void BindDdl()
{
SqlConnection
con = new SqlConnection("Data Source=DELL-PC\\SQLEXPRESS;Initial
Catalog=Demo;Integrated Security=True");
string
queryValidate = "Select * from
CountryName";
DataTable
objdt = new DataTable();
SqlDataAdapter
da = new SqlDataAdapter(queryValidate,
con);
da.Fill(objdt);
if
(objdt.Rows.Count > 0)
{
DropDownList1.DataSource =
objdt;
DropDownList1.DataTextField =
"CountryName";
DropDownList1.DataValueField
= "Id";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0,
"Select Country");
}
}
}
}
|
In above code I have created a function. In this first I have created a sel connection and in datatable I have used sql adapter to retrieve the value.
After fetting the value I have bind the value to the
dropdown list. So we have done. Run the application and check the output.
0 comments:
Please let me know your view