Ok darsh you will have to first change your database table structures like this
CREATE TABLE Country
(
CountryID INT IDENTITY,
CountryName VARCHAR(100)
)
CREATE TABLE State
(
StateID INT IDENTITY,
CountryID INT,
StateName VARCHAR(100)
)
Now the CountryID Column in Country Table and StateID Column in State Table are auto generated.
Now you will have to write the following codes on Country.aspx Page
//--------------------------Country.aspx Page-----------------------------
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;
using System.Configuration;
namespace SampleProject
{
public partial class Country : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyCon"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Country(CountryName) VALUES(@CN)", con);
cmd.Parameters.Add(new SqlParameter("@CN", txtCountry.Text));
int i = cmd.ExecuteNonQuery();
Response.Write(i.ToString() + "Row(s) updated Successfully");
}
protected void btnClear_Click(object sender, EventArgs e)
{
Response.Redirect("~/Country.aspx");
}
}
}
Now you will have to write the following codes on State.aspx Page
//----------------------------------State.aspx Page--------------------
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;
using System.Configuration;
namespace SampleProject
{
public partial class State : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dataTable = new DataTable();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyCon"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("SELECT CountryID, CountryName FROM Country", con);
SqlDataReader sqlDataReader = cmd.ExecuteReader();
dataTable.Load(sqlDataReader);
ddlCountry.DataSource = dataTable;
ddlCountry.DataTextField = "CountryName";
ddlCountry.DataValueField = "CountryID";
ddlCountry.DataBind();
}
else
{
ddlCountry.SelectedItem.Value = ddlCountry.SelectedItem.Value;
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyCon"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO State(CountryID,StateName) VALUES(@CI,@SN)", con);
cmd.Parameters.Add(new SqlParameter("@CI", Convert.ToInt32(ddlCountry.SelectedItem.Value)));
cmd.Parameters.Add(new SqlParameter("@SN", txtState.Text));
int i = cmd.ExecuteNonQuery();
Response.Write(i.ToString() + "Row(s) updated Successfully");
}
}
}
and check whether it works.