Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey,

I have a form that user can add a new client and it inserts data into database by a button click.

this is my code that worked perfectly

C#
private void button1_Click(object sender, EventArgs e)
{

    string sqlText = "SELECT MAX(customerName) FROM Customer";

    SqlConnection sqlConn = new SqlConnection(@"Data Source=Admin-PC\SQLEXPRESS;Initial Catalog=Couriers;Integrated Security=True");

    SqlCommand command = new SqlCommand(sqlText, sqlConn);


    SqlDataAdapter da = new SqlDataAdapter();
    da.InsertCommand = new SqlCommand("INSERT INTO Customer VALUES(@customerName,@CustomerAddress,@CustomerContact,@VatNo)", sqlConn);
    da.InsertCommand.Parameters.Add("@customerName", SqlDbType.VarChar).Value = textBox4.Text;
    da.InsertCommand.Parameters.Add("@CustomerAddress", SqlDbType.VarChar).Value = textBox2.Text;
    da.InsertCommand.Parameters.Add("@CustomerContact", SqlDbType.Int).Value = textBox3.Text;
    da.InsertCommand.Parameters.Add("@VatNo", SqlDbType.Int).Value = textBox5.Text;
    
    sqlConn.Open();
    da.InsertCommand.ExecuteNonQuery();
    sqlConn.Close();
    MessageBox.Show("Client Successfully added");
    this.Close();

}


Now i added CustomerId into my SQL table and having problems with this code.
The customerId must be generated automatically dont want user to input id, but now the code is wrong
Posted
Updated 11-Sep-12 23:36pm
v3

1 solution

In your table(Sql Table), truncate your all data (If required keep a backup). Now, alter your column CustomerId and set it as IDENTITY. After that you don't suppose to insert the value in identity column.
Try this:
SQL
alter table table1 add col3 int identity(1,1)

Refer this[^] for more information on identity columns.


--Amit
 
Share this answer
 
Comments
Mohamed Mitwalli 12-Sep-12 5:53am    
5+
_Amy 12-Sep-12 5:55am    
Thanks Mohamed. :)
GoggatjieLiesl 12-Sep-12 6:05am    
Great it works just the way i wanted it to.
Thanks
_Amy 12-Sep-12 6:23am    
Welcome. :)
GoggatjieLiesl 16-Sep-12 3:13am    
Hey, Can i ask you one more question in this table i have a foreign key aswell, now the form again doesnt want to run how do i fix the foreign key issue i tried the same way with identity but only allowed one identity per table. In my foreign key main table i did specify it as identity

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