How to get Auto ID when using ADO.NET?

Results 1 to 2 of 2

Thread: How to get Auto ID when using ADO.NET?

  1. #1
    Join Date
    Dec 1969

    Default How to get Auto ID when using ADO.NET?

    I&#039;m using the following code, to insert a new row into a SQL Server table.<BR><BR>public int MakeNewUser(string strConn, string strUsername, string strEmail, string strPassword, string strFamilyName, int intICQ, int intMessenger) {<BR> // Create a new Connection and SqlDataAdapter<BR> System.Data.SqlClient.SqlConnection myConnection = new System.Data.SqlClient.SqlConnection(GetApp(strConn ));<BR> System.Data.SqlClient.SqlDataAdapter mySqlDataAdapter = new System.Data.SqlClient.SqlDataAdapter("SELECT TOP 1 * FROM UserTable", myConnection);<BR> System.Data.DataSet myDataSet = new System.Data.DataSet();<BR> System.Data.DataRow myDataRow;<BR> <BR> // Create command builder. This line automatically generates the update commands for you, so you don&#039;t have to provide or create your own.<BR> System.Data.SqlClient.SqlCommandBuilder mySqlCommandBuilder = new System.Data.SqlClient.SqlCommandBuilder(mySqlDataA dapter);<BR> <BR> // Set the MissingSchemaAction property to AddWithKey because Fill will not cause primary key & unique key information to be retrieved unless AddWithKey is specified.<BR> mySqlDataAdapter.MissingSchemaAction = System.Data.MissingSchemaAction.AddWithKey;<BR> <BR> mySqlDataAdapter.Fill(myDataSet, "UserTable");<BR> int intNewUser = 0;<BR> myDataRow = myDataSet.Tables["UserTable"].NewRow();<BR> //myDataRow["CustomerId"] = "NewID";<BR> myDataRow["UserName"] = strUsername;<BR> myDataRow["UserEmail"] = strEmail;<BR> myDataRow["UserPassword"] = strPassword;<BR> myDataRow["UserFamilyName"] = strFamilyName;<BR> myDataRow["UserMoney"] = 0;<BR> myDataRow["UserTurn"] = 0;<BR> myDataRow["UserCreated"] = DateTime.Now;<BR> myDataRow["UserICQ"] = intICQ;<BR> myDataRow["UserMessenger"] = intMessenger;<BR> //int NewUser = myDataRow["UserID"];<BR> myDataSet.Tables["UserTable"].Rows.Add(myDataRow);<BR> //myDataSet.Close();<BR> txtErrorMsg.Text = myDataRow["UserID"].ToString();<BR> mySqlDataAdapter.Update(myDataSet, "UserTable");<BR><BR> myConnection.Close();<BR> return intNewUser;<BR>}<BR><BR>It was my meaning to let the function return the Autoincrement ID from the inserted column, but, how do I do it?

  2. #2
    Join Date
    Dec 1969

    Default RE: How to get Auto ID when using ADO.NET?

    use select @@Identity from table before you close your connection.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts