Hi, this is my first job in UK, so need bit of help. The problem goes like this. I have an existing SQL database where there are 2 user tables. One contains only field.U_Id(int) not null and other is user_details table where there are fields like user_id(int), username and so on. While I am trying to insert values into the usertable, if i leave the user id field, then it throws an exception that the field cannot contain nulls, which is right but I want to know a way of incrementing the userid by 1 in both tables.

My code goes like this.

  string connString = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(connString))
               string insertstr = " insert into ct_user(User_Id,name,password,email)values(@UserId,@UserName,@Password,@email)";
                var cmdtext = new SqlCommand(insertstr,conn);
                cmdtext.Parameters.AddWithValue("@UserName", txtUserName.Text);
                cmdtext.Parameters.AddWithValue("@Password", txtPassword.Text);
                cmdtext.Parameters.AddWithValue("@Email", txtEmail.Text);
                Console.WriteLine("Your account has been successfully created", conn);

Thanks and Regards,
Pradeep Khatri

Dont include the ID in the insert statement, if the DB is set to auto inc, it will do it all for you.

I have tried that also, it still throws an error.

and in both tables it is not set as autoincrement field it is an int field.

Then you need to put the int in yourself, and ensure its unique, once you've done that if it still errors, we need some errors, and the code it executed.

but that is hardcoding the userid, which i dont want to do..wht i want is it automatically adds to the existing number which is there in both tables..for example, if the last userid was 675 , and if i create 2 users through front end , they should 676 and 677 respectively.

Well, then thats the point of getting the DB to do it for you, however, I didnt say hard code it, i said you have to insert the code to add the int, I wasnt suggesting you fixed the number..

So, you have the spec for your new bit of code, as you said, you need to get the last userid add 1 to it, and put your new line in

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.