473,659 Members | 3,117 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Retrieve new row identity in C#

Hi,
I'm having a bit of difficulty in getting the identity of a new row
using the SCOPE_IDENTITY( ) function in SQLServer 2000.

I've added the following code: 'set @LastID = SCOPE_IDENTITY( )' to the
end of the select statement in the Stored Procedure, and have the
following code in the aspx.cs file:

SqlCommand cmdEntry;
SqlParameter prmEntryID = new
SqlParameter("R ETURN_VALUE",Sq lDbType.Int);
prmEntryID.Dire ction = ParameterDirect ion.ReturnValue ;

cmdEntry = new SqlCommand("kb_ Add_Entry", conn);
cmdEntry.Comman dType = CommandType.Sto redProcedure;
cmdEntry.Parame ters.Add ("@kb_entry_des cription", txtDescription. Text);
cmdEntry.Parame ters.Add ("@kb_entry_res olution", txtResolution.T ext);
cmdEntry.Parame ters.Add ("@kb_entry_mai ncategory",
ddlCategories.S electedItem.Val ue);
cmdEntry.Parame ters.Add ("@kb_entry_ent eredby", "Mark");
cmdEntry.Parame ters.Add ("@kb_entry_sou rce", txtSource.Text) ;
cmdEntry.Parame ters.Add ("@kb_entry_key words", txtKeywords.Tex t);
cmdEntry.Parame ters.Add (prmEntryID);
conn.Open();
cmdEntry.Execut eNonQuery();
string strEntryID =
cmdEntry.Parame ters["RETURN_VAL UE"].Value.ToString ();
conn.Close();

However, when I run the code, I get the following error: 'Error
converting data type nvarchar to int.'

Can anyone help?

Thanks in advance,
Mark

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #1
3 1697
hi,

if you are running an stored procedure then jusr return it :

in the SP:
insert into XXX values YYY
SELECT @@IDENTITY

in the CS code:
int id = Convert.toInt32 ( cmd.ExecutyScal ar() );

cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Mark" <an*******@devd ex.com> wrote in message
news:ex******** ******@tk2msftn gp13.phx.gbl...
Hi,
I'm having a bit of difficulty in getting the identity of a new row
using the SCOPE_IDENTITY( ) function in SQLServer 2000.

I've added the following code: 'set @LastID = SCOPE_IDENTITY( )' to the
end of the select statement in the Stored Procedure, and have the
following code in the aspx.cs file:

SqlCommand cmdEntry;
SqlParameter prmEntryID = new
SqlParameter("R ETURN_VALUE",Sq lDbType.Int);
prmEntryID.Dire ction = ParameterDirect ion.ReturnValue ;

cmdEntry = new SqlCommand("kb_ Add_Entry", conn);
cmdEntry.Comman dType = CommandType.Sto redProcedure;
cmdEntry.Parame ters.Add ("@kb_entry_des cription", txtDescription. Text);
cmdEntry.Parame ters.Add ("@kb_entry_res olution", txtResolution.T ext);
cmdEntry.Parame ters.Add ("@kb_entry_mai ncategory",
ddlCategories.S electedItem.Val ue);
cmdEntry.Parame ters.Add ("@kb_entry_ent eredby", "Mark");
cmdEntry.Parame ters.Add ("@kb_entry_sou rce", txtSource.Text) ;
cmdEntry.Parame ters.Add ("@kb_entry_key words", txtKeywords.Tex t);
cmdEntry.Parame ters.Add (prmEntryID);
conn.Open();
cmdEntry.Execut eNonQuery();
string strEntryID =
cmdEntry.Parame ters["RETURN_VAL UE"].Value.ToString ();
conn.Close();

However, when I run the code, I get the following error: 'Error
converting data type nvarchar to int.'

Can anyone help?

Thanks in advance,
Mark

*** Sent via Developersdex http://www.developersdex.com ***

Nov 17 '05 #2
Hi,
Thanks for replying. Unfortunately I'm still getting the same error
message, this time on the intEntryID =
Convert.ToInt32 (cmdEntry.Execu teScalar()); line...

Mark

*** Sent via Developersdex http://www.developersdex.com ***
Nov 17 '05 #3
hi

well I assume that the PK was an integer

do tihs:
object o = cmd.ExecutyScal ar();
and put a breakpoint after that line, you will see the type of o , and you
could use the correct method/cast
cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation

"Mark" <an*******@devd ex.com> wrote in message
news:%2******** **********@TK2M SFTNGP09.phx.gb l...
Hi,
Thanks for replying. Unfortunately I'm still getting the same error
message, this time on the intEntryID =
Convert.ToInt32 (cmdEntry.Execu teScalar()); line...

Mark

*** Sent via Developersdex http://www.developersdex.com ***

Nov 17 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
261
by: Alberto | last post by:
The following example works, but the retrival of the returned identity does not work 'Set Command Object Propertie objCommand.ActiveConnection = GV_objConnectio objCommand.CommandText = "DAO.RCCBABY_Add_Test objCommand.CommandType = ADODB.CommandTypeEnum.adCmdStoredPro 'Set The Parameter objCommand.Parameters.Append(objCommand.CreateParameter("TestKey", ADODB.DataTypeEnum.adInteger, ADODB.ParameterDirectionEnum.adParamReturnValue)...
2
5455
by: WhiteEagl | last post by:
Hello, I would need some help with this identity column problem in SQLServer. I have a database with two tables. The Parent table has an Identity column. Parent (ParentID IDENTITY, Name) Child (ChildID, Name, ParentID)
1
1921
by: mg | last post by:
Can someone give me C# code that will connect me to Active Directory, let me give Active Directory a user's name and retrieve his/her e-mail address. I need this for a WebForm.
1
2887
by: loreille | last post by:
To insert a record in a Ms Access database and be able to retrieve the newly created ID (autonumber) I used the code below (code 1). Now, the problem is that this is not very secure and that, if for example an insertion contains a ' or a " this code fails. It is much better to work with @parameters. So could someone change my code to make it work with @parameters and
4
5075
by: jay | last post by:
I am using the dataset object to add a row to a sql server database in vb.net code, as follows: dim drow as DataRow dim cmdBld as new SqlCommandBuilder(mySqlDataAdapter) ds.tables(0).NewRow() drow("field1") = data for field 1 and so forth ds.tables(0).rows.add(drow) cmdBld = New SqlCommandBuilder(mySqlDataAdapter)
9
2928
by: Jeremy | last post by:
I have a situation where i am trying to run two query's and retrieve one record from each query, then using Union combine them into one recordset. The First Query is strait forward and should just return the matching record however the second query needs to find a random record and return it. The union is causing me some trouble. It seems that any method i try to find a random record just causes an error. Here is an example of a query...
13
3422
by: kev | last post by:
Hi all, I have created a database for equipments. I have a form to register the equipment meaning filling in all the particulars (ID, serial, type, location etc). I have two buttons at the end of the form which is submit and cancel. After i have clicked submit, the information is stored directly into my corresponding database table. My problem here is i need to retrieve back the information submitted to display all the data that the...
2
4370
by: feets | last post by:
OK first time poster, so hello everyone in advance. Right i'm sure this is a simple problem to solve, but I'm just getting the hang of SQL 2000. What I've got is a form where I input the values and then through a procedure these values are inserted into a table. That's fine. However I now need to open a subform which is linked by the ID field created through the first procedure. How do I retrieve that value back into the form?? The...
2
1589
by: =?Utf-8?B?SmVmZlAtPg==?= | last post by:
I want to retrieve an image file (TIF) convert it to a bmp file and enable sizing. I know how to do the converting & sizing part, and store any atributes to file location in the webconfig, what I don't know is how to get the image file. The only way that I've got it working was to Impersonate a user login at the other server.
0
8428
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8335
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8747
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8528
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7356
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
1737
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.