consider a table in your database .. else run the script to create
Create table person (
id int identity(1,1) not null,
name varchar(100) not null,
age int not null
)
-----------------
// C# sample code, should be in a proper .cs file to be executed
// some imports
using System;
using System.Data;
using System.Data.SqlClient;
// more imports
// ....
// some code
String connectionString = ""Persist Security Info=False;User ID=sa;Password=sa;Initial Catalog=master;Data Source=localhost;
// this is the query which we will require
String query = "insert into person (name, age) values (@NAME, @AGE);select @ROWID = @@identity";
DataTable dt = new DataTable();
dt.Columns.Add("ID", System.Type.GetType("System.Int32"));
dt.Columns.Add("NAME", System.Type.GetType("System.String"));
dt.Columns.Add("AGE", System.Type.GetType("System.Int32"));
dt.Rows.Add(new object[] {-1, "max", 10});
// check dt.Rows[0]["ID"] value it will be -1
// inserting the above table into database
SqlDataAdapter myAdapter =new SqlDataAdapter();
SqlConnection myConnection = new SqlConnection(ConnectionString);
myConnection.Open();
SqlCommand cmd = new SqlCommand(query, myConnection);
SqlParameter parmRowId =
cmd.Parameters.Add("@ROWID",DbType.Int32);
parmRowId.SourceColumn = "ID";
parmRowId.SourceVersion = DataRowVersion.Original;
parmRowId.Direction = ParameterDirection.Output;
SqlParameter parmID =
cmd.Parameters.Add("@NAME",DbType.Int32);
parmID.SourceColumn = "NAME";
parmID.SourceVersion = DataRowVersion.Original;
SqlParameter parmID =
cmd.Parameters.Add("@AGE",DbType.Int32);
parmID.SourceColumn = "AGE";
parmID.SourceVersion = DataRowVersion.Original;
myAdapter.InsertCommand = cmd;
// required to get back the auto-incrmented value
cmd.UpdatedRowSource = UpdateRowSource.OutputParameters;
myAdapter.Update(datatable);
// now check dt.Rows[0]["ID"] value it should be 1 or some auto-incremented value
// the above style can be used with your typed dataset too
// ... more code