Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
two textbox(id,name) and one command button(save) in my form . i want when i click on save button then popup message show auto generate id no.
i used id = identity increment in database.
please help..
Posted
Comments
Emre Ataseven 9-Apr-14 13:46pm    
Depends on your DB type, what is it?
manish7664 11-Apr-14 1:50am    
datatype of id is int.

To get the last enter auto generated id use

SQL
USE tempdb
GO
CREATE TABLE TZ (
   Z_id  int IDENTITY(1,1)PRIMARY KEY,
   Z_name varchar(20) NOT NULL)

INSERT TZ
   VALUES ('Lisa')
INSERT TZ
   VALUES ('Mike')
INSERT TZ
   VALUES ('Carla')

SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY] FROM TZ


SCOPE_IDENTITY() return the last id value being autogenerated
 
Share this answer
 
Comments
manish7664 9-Apr-14 7:27am    
sorry sir but i want c# code.
MessageBox.Show("Your ID No. is- ");

private void Save_Click(object sender, EventArgs e)
{
conn = new SqlConnection(@"Data Source..........");
conn.Open();
SqlCommand command = new SqlCommand();
command.CommandText = "insert into test(name)values('" + textBox2.Text + "'")";
command.Connection = conn;
command.ExecuteNonQuery();
MessageBox.Show("Your ID No. is- ");
}
Er. Puneet Goel 9-Apr-14 7:34am    
Ok, then once you saved the record with the following code

conn = new SqlConnection(@"Data Source..........");
conn.Open();
SqlCommand command = new SqlCommand();
command.CommandText = "insert into test(id,name)values('" + textbox1.text + "','" + textBox2.Text + "'")";
command.Connection = conn;
command.ExecuteNonQuery();

Here, get the value of last saved ID with folowing query
"SELECT Max(id) FROM test"

And display this.
After your call to
C#
command.ExecuteNonQuery();

do a
C#
command.CommandText = "SELECT @@IDENTITY As myInsertID";
int lastId = (int)command.ExecuteScalar();
MessageBox.Show(string.Format("Your ID No. is {0}", lastId));

@@Identity is also safe in a multi-user environment. SCOPE_IDENTITY() and SELECT Max(id) are not!
 
Share this answer
 
Comments
manish7664 11-Apr-14 13:37pm    
Thanks Mr. Bernhard for reply. i have modified my code as per your suggestion but when i click on save button then one error coming.
Error ---> Object reference not set to an instance of an object.
Error line ---> command.CommandText = "SELECT @@IDENTITY As myInsertID";
Bernhard Hiller 14-Apr-14 2:12am    
You have to do that in a place where "command" is still in scope!

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