Here is your solution
Database design
Run below query on sql server database which I have considered in below example
Please note that you may have to update connection string in below code for server name and database name
CREATE TABLE tblStateMaster (Id INT IDENTITY(1,1),State NVARCHAR(50))
CREATE TABLE tblCityMaster (Id INT IDENTITY(1,1),StateId Int, City NVARCHAR(50))
--
INSERT INTO tblStateMaster(State)
SELECT 'State1'
UNION
SELECT 'State2'
1) Create one windows form and add controls as per instruction here:
1.1) Add one combbox - cmbState
1.2) Add one combobox - cmbCity
1.3) Add one button - btnAddCity
2) Double click anywhere in the form to open cs code window
3) Add below three declarations after form load
public static OleDbConnection Conn = new OleDbConnection();
public static string ATCregionId;
4) Add below three methods after that
-- Connect to sql server database
public static bool Connect()
{
string conn = @"Provider=SQLNCLI;Server=sqlservertest;Database=testdb;Uid=sa;Pwd=sa123;";
if (Conn.State == System.Data.ConnectionState.Open)
Conn.Close();
Conn.ConnectionString = conn;
Conn.Open();
return true;
}
-- Refresh state combo box , City combo box
public void RefreshState()
{
cmbstate.Items.Clear();
OleDbDataReader reader;
int dbRecords;
dbRecords = 0;
OleDbCommand command = new OleDbCommand();
command.CommandText = "SELECT State FROM tblStateMaster";
try
{
Connect();
command.Connection = Conn;
reader = command.ExecuteReader();
int index = 0;
while (reader.Read())
{
string result = reader.GetString(0);
cmbstate.Items.Add(result.ToString());
index++;
}
reader.Close();
Conn.Close();
}
catch (Exception ex)
{
}
}
public void RefreshCity()
{
cmbcity.Items.Clear();
OleDbDataReader reader;
int dbRecords;
dbRecords = 0;
OleDbCommand command = new OleDbCommand();
command.CommandText = "SELECT City FROM tblCityMaster";
try
{
Connect();
command.Connection = Conn;
reader = command.ExecuteReader();
int index = 0;
while (reader.Read())
{
string result = reader.GetString(0);
cmbcity.Items.Add(result.ToString());
index++;
}
reader.Close();
Conn.Close();
}
catch (Exception ex)
{
}
}
5) Add code to save city button
private void button1_Click(object sender, EventArgs e)
{
Connect();
OleDbCommand selectCommand = new OleDbCommand();
OleDbDataReader reader;
int dbRecords;
dbRecords = 0;
selectCommand.CommandText = "SELECT City FROM tblCityMaster WHERE City='" + cmbcity + "'";
selectCommand.Connection = Conn;
reader = selectCommand.ExecuteReader();
if (reader.Read())
MessageBox.Show("City already added");
else
{
OleDbCommand insertCommand = new OleDbCommand("INSERT INTO tblCityMaster( StateId,City) SELECT sm.Id, '"+cmbcity.Text+"' FROM tblStateMaster sm WHERE State='" + cmbstate.Text + "'", Conn);
try
{
int count = insertCommand.ExecuteNonQuery();
Conn.Close();
RefreshCity();
}
catch (Exception ex)
{
}
}
}
Hope this helps. If yes then vote and accept the answer :)