Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have form where i have 2 combo boxes for state and city . I have inserted all states now i want user to insert city by selecting appropriate state. But the thing is when i click insert button city-id gets null value in city table and city-id is primary so it can't be null
So plz hepl..
1) How to insert city in table with autoassigned city id and it should be unique for each city
2) How to show recently added city into combo box
Posted
Updated 31-May-14 20:33pm
v2
Comments
[no name] 31-May-14 17:20pm    
Help you with what? You do realize that we cannot see your code, your project, your database, your monitor or read your mind, right?
ZurdoDev 31-May-14 22:22pm    
What is your problem?
Member 9671810 31-May-14 22:59pm    
The problem is i cannot insert city at the same time i register my user
RDBurmon 1-Jun-14 2:34am    
Hope my solution works for you. :)
Member 9671810 3-Jun-14 5:30am    
plz read read my code and problem posted above..

the button city-id gets null value as it is primary it does not insert null, you say.

I think what you are trying to do is to insert a city name that a user has written in a textBox on a form.

What you should do is to Write it to the database as follows:

1) Make sure your database table field City ID primary key is not automatically incremented (this you do in the database)
2) Whenever you write a New city name into the database table, increment the primary key value With a query like this:

insert into cities (id,cityname) values ( (select max(id)+1 from cities), 'Sidney');

maybe you Call Your database table something else but here it is cities, and the primary key is named id, the Field for the city name is.. cityname...
 
Share this answer
 
v2
Comments
RDBurmon 1-Jun-14 2:29am    
My +5
Member 9671810 3-Jun-14 13:27pm    
dis worked a bit. but the thing is i cannot pass the parameter when i m inserting the the whole form in database.
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
sq
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
C#
public static OleDbConnection Conn = new OleDbConnection();
public static string ATCregionId;


4) Add below three methods after that

-- Connect to sql server database
C#
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
C#
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

C#
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 :)
 
Share this answer
 
Comments
gggustafson 1-Jun-14 14:11pm    
I do not see how a city is added to a state. We could have Los Angles Connecticut which does not exist. Don't you need a city-to-state table?
Member 9671810 3-Jun-14 4:50am    
thanks a lot sir...i understand your code. but the thing is i want to insert when i click submit button..
here's my code..


private void button1_Click(object sender, EventArgs e)
{
try
{
string fname;
string mname;
string lname;
fname = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(txtfname.Text.ToLower());
mname = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(txtmname.Text.ToLower());
lname = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(txtlname.Text.ToLower());


// ( strdate , "d/MM/yyyy", CultureInfo.InvariantCulture).ToString()
SqlCommand cmd = new SqlCommand("insert_registration");
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@sname", cmbname.Text);
cmd.Parameters.AddWithValue("@fname", fname.ToString());
cmd.Parameters.AddWithValue("@mname", mname.ToString());
cmd.Parameters.AddWithValue("@lname", lname.ToString());
cmd.Parameters.AddWithValue("@address", rchtxtaddress.Text);
cmd.Parameters.AddWithValue("@state_id", cmbstate.SelectedValue);

if (cmbcity.SelectedValue == null)
{
cmbcity_SelectedIndexChanged(sender, e);
int id;
bool paresOK = Int32.TryParse(cmbstate.SelectedValue.ToString(), out id);
SqlDataAdapter cityda = new SqlDataAdapter("select city_name , city_id from city where state_id = '" + id + "' ", con);
DataTable citydt = new DataTable();
cityda.Fill(citydt);
cmbcity.DataSource = citydt;
cmbcity.DisplayMember = "city_name";
cmbcity.ValueMember = "city_id";
//int city = Int16.Parse(cmbcity.ValueMember);
cmd.Parameters.AddWithValue("@city_id", Int16.Parse("city_id++"));
//cmbcity.MaxDropDownItems + 1);
// cmbstate.DropDownStyle = ComboBoxStyle.DropDownList;
// SqlDataAdapter cityda1 = new SqlDataAdapter("select * from city where state_id = '" + +"'"
}
else
{
cmd.Parameters.AddWithValue("@city_id", cmbcity.SelectedValue);
}

cmd.Connection = con;
int check = 0;
con.Open();
check = cmd.ExecuteNonQuery();
con.Close();
}

catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

private void cmbmemstate1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlDataAdapter stateda = new SqlDataAdapter("select * from state", con);
DataTable statedt = new DataTable();
stateda.Fill(statedt);
cmbmemstate1.DataSource = statedt;
cmbmemstate1.DisplayMember = "state_name";
cmbmemstate1.ValueMember = "state_id";
cmbmemstate1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
cmbmemstate1.AutoCompleteSource = AutoCompleteSource.ListItems;
}

but dis aint working..
i don't want another button to insert only city...
the thing is if the city is not in list so then the user can insert city... dat's all i want..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900