Create 2 or 3 tables in SQL,
Assign a primary key in first table(e.g. Country table).
Primary & foreign key in second table,(e.g. State Table) etc.
Add a connection string in web.config.
Create a class file (e.g. code).
- using System.Linq;
- using System.Web;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- namespace WebApplication1 {
- public class code {
- SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["con"].ToString());
- public DataSet select(string s) {
- DataSet ds = new DataSet();
- SqlDataAdapter da = new SqlDataAdapter(s, con);
- da.Fill(ds);
- return ds;
- }
- public int insert(string s) {
- int i;
- SqlCommand cmd = new SqlCommand(s, con);
- con.Open();
- i = cmd.ExecuteNonQuery();
- con.Close();
- return i;
- }
- }
- }
Code starts here:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using System.Data;
- using System.Data.SqlClient;
- namespace WebApplication1 {
- public partial class DDList: System.Web.UI.Page {
- DataSet ds = new DataSet();
- code gs = new code();
- string s;
- protected void Page_Load(object sender, EventArgs e) {
- if (!IsPostBack) {
- s = "Select * from tbl_Country";
- ds = gs.select(s);
- if (ds.Tables[0].Rows.Count > 0) {
- DropDownList1.DataTextField = "country_name";
- DropDownList1.DataValueField = "country_id";
- DropDownList1.DataSource = ds;
- DropDownList1.DataBind();
-
- }
- }
- }
- protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e) {
- s = "select * from tbl_State where country_id = '" + DropDownList1.SelectedValue + "'";
- ds = gs.select(s);
- if (ds.Tables[0].Rows.Count > 0) {
- DropDownList2.DataTextField = "state_name";
- DropDownList2.DataValueField = "state_id";
- DropDownList2.DataSource = ds;
- DropDownList2.DataBind();
-
- }
- }
- protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e) {
- s = "select * from tbl_city where state_id = '" + DropDownList2.SelectedValue + "'";
- ds = gs.select(s);
- if (ds.Tables[0].Rows.Count > 0) {
- DropDownList3.DataTextField = "city_name";
- DropDownList3.DataValueField = "city_id";
- DropDownList3.DataSource = ds;
- DropDownList3.DataBind();
-
- }
- }
- }
- }
Note: Don't forget to set AutoPostBack="true".