473,769 Members | 7,558 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using GUID and SQL in code

Hi, I don't get it I cannot get this to work, can somebody give me a hint
Table1 contains a field Id which is a GUID as primary key and DATA a string,
I want to insert a new row but it does not work.
void gv_RowCommand(O bject sender, GridViewCommand EventArgs e)
{
ClientScript.Re gisterStartupSc ript(GetType(), "MyAlert2",
"alert('Command =" + e.CommandName + "');", true);
if (e.CommandName == "New")
{
SqlCommand cmd = new SqlCommand();

//First problem How do I make a GUID?
SqlGuid g = new SqlGuid("3AAAAA AA-BBBB-CCCC-DDDD-2EEEEEEEEEEE");
//Second problem, how do I use the GUID in the Insert
cmd.CommandText = "INSERT INTO dbo.Table1
Values("+g.ToSt ring()+",'tst') "; //?????
cmd.CommandType = CommandType.Tex t ;
SqlConnection sqlConnection1 = new
SqlConnection(S qlDataSource1.C onnectionString );
cmd.Connection = sqlConnection1;
sqlConnection1. Open();
cmd.ExecuteNonQ uery();
sqlConnection1. Close();
GridView1.DataB ind();
}
}
Aug 12 '08 #1
4 5521
SqlGuid guid = new SqlGuid(Guid.Ne wGuid());
string str = "some string here";

string sql = "INSERT INTO TABLE VALUES (@guid,@str)";

SqlCommand cmd = new SqlCommand();
cmd.Parameters. AddWithValue("@ guid", guid);
cmd.Parameters. AddWithValue("@ str", str);
--
Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA

Subscribe to my blog
http://gregorybeamer.spaces.live.com/lists/feed.rss

or just read it:
http://gregorybeamer.spaces.live.com/

*************** *************** **************
| Think outside the box! |
*************** *************** **************
"Marc" <no*****@chello .nlwrote in message
news:%2******** ********@TK2MSF TNGP03.phx.gbl. ..
Hi, I don't get it I cannot get this to work, can somebody give me a hint
Table1 contains a field Id which is a GUID as primary key and DATA a
string, I want to insert a new row but it does not work.
void gv_RowCommand(O bject sender, GridViewCommand EventArgs e)
{
ClientScript.Re gisterStartupSc ript(GetType(), "MyAlert2",
"alert('Command =" + e.CommandName + "');", true);
if (e.CommandName == "New")
{
SqlCommand cmd = new SqlCommand();

//First problem How do I make a GUID?
SqlGuid g = new SqlGuid("3AAAAA AA-BBBB-CCCC-DDDD-2EEEEEEEEEEE");
//Second problem, how do I use the GUID in the Insert
cmd.CommandText = "INSERT INTO dbo.Table1
Values("+g.ToSt ring()+",'tst') "; //?????
cmd.CommandType = CommandType.Tex t ;
SqlConnection sqlConnection1 = new
SqlConnection(S qlDataSource1.C onnectionString );
cmd.Connection = sqlConnection1;
sqlConnection1. Open();
cmd.ExecuteNonQ uery();
sqlConnection1. Close();
GridView1.DataB ind();
}
}
Aug 12 '08 #2
I am beginning to loose faith now.... I am getting the message:

String or binary data would be truncated.
The statement has been terminated.

This is the code:

SqlCommand cmd = new SqlCommand();
SqlGuid guid = new SqlGuid(Guid.Ne wGuid());
string str = "some string here";
string sql = "INSERT INTO TABLE1 VALUES (@guid,@str)";
cmd.CommandText = sql;
cmd.Parameters. AddWithValue("@ guid", guid);
cmd.Parameters. AddWithValue("@ str", str);
cmd.CommandType = CommandType.Tex t ;
SqlConnection sqlConnection1 = new
SqlConnection(S qlDataSource1.C onnectionString );
cmd.Connection = sqlConnection1;
sqlConnection1. Open();
cmd.ExecuteNonQ uery();
sqlConnection1. Close();
GridView1.DataB ind();

Server Error in '/H4SP2' Application.
String or binary data would be truncated.
The statement has been terminated.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.

Exception Details: System.Data.Sql Client.SqlExcep tion: String or binary data
would be truncated.
The statement has been terminated.

Source Error:

Line 40: cmd.Connection = sqlConnection1;
Line 41: sqlConnection1. Open();
Line 42: cmd.ExecuteNonQ uery();
Line 43: sqlConnection1. Close();
Line 44: GridView1.DataB ind();
Source File: c:\Documents and Settings\Marc wentink\Mijn documenten\Visu al
Studio 2005\WebSites\H 4SP2\Default.as px.cs Line: 42

Stack Trace:

[SqlException (0x80131904): String or binary data would be truncated.
The statement has been terminated.]
System.Data.Sql Client.SqlConne ction.OnError(S qlException exception,
Boolean breakConnection ) +95
System.Data.Sql Client.SqlInter nalConnection.O nError(SqlExcep tion
exception, Boolean breakConnection ) +82
System.Data.Sql Client.TdsParse r.ThrowExceptio nAndWarning(Tds ParserStateObje ct
stateObj) +346
System.Data.Sql Client.TdsParse r.Run(RunBehavi or runBehavior, SqlCommand
cmdHandler, SqlDataReader dataStream, BulkCopySimpleR esultSet
bulkCopyHandler , TdsParserStateO bject stateObj) +3244
System.Data.Sql Client.SqlComma nd.FinishExecut eReader(SqlData Reader ds,
RunBehavior runBehavior, String resetOptionsStr ing) +186
System.Data.Sql Client.SqlComma nd.RunExecuteRe aderTds(Command Behavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
+1121
System.Data.Sql Client.SqlComma nd.RunExecuteRe ader(CommandBeh avior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method,
DbAsyncResult result) +334
System.Data.Sql Client.SqlComma nd.InternalExec uteNonQuery(DbA syncResult
result, String methodName, Boolean sendToPipe) +407
System.Data.Sql Client.SqlComma nd.ExecuteNonQu ery() +149
_Default.gv_Row Command(Object sender, GridViewCommand EventArgs e) in
c:\Documents and Settings\Marc wentink\Mijn documenten\Visu al Studio
2005\WebSites\H 4SP2\Default.as px.cs:42
System.Web.UI.W ebControls.Grid View.OnRowComma nd(GridViewComm andEventArgs
e) +96
System.Web.UI.W ebControls.Grid View.HandleEven t(EventArgs e, Boolean
causesValidatio n, String validationGroup ) +121
System.Web.UI.W ebControls.Grid View.RaisePostB ackEvent(String
eventArgument) +215
System.Web.UI.W ebControls.Grid View.System.Web .UI.IPostBackEv entHandler.Rais ePostBackEvent( String
eventArgument) +31
System.Web.UI.P age.RaisePostBa ckEvent(IPostBa ckEventHandler
sourceControl, String eventArgument) +32
System.Web.UI.P age.RaisePostBa ckEvent(NameVal ueCollection postData) +244
System.Web.UI.P age.ProcessRequ estMain(Boolean
includeStagesBe foreAsyncPoint, Boolean includeStagesAf terAsyncPoint) +3838

Version Information: Microsoft .NET Framework Version:2.0.507 27.42; ASP.NET
Version:2.0.507 27.42
"Cowboy (Gregory A. Beamer)" <No************ @comcast.netNoS pamMschreef in
bericht news:uN******** ******@TK2MSFTN GP06.phx.gbl...
SqlGuid guid = new SqlGuid(Guid.Ne wGuid());
string str = "some string here";

string sql = "INSERT INTO TABLE VALUES (@guid,@str)";

SqlCommand cmd = new SqlCommand();
cmd.Parameters. AddWithValue("@ guid", guid);
cmd.Parameters. AddWithValue("@ str", str);
--
Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA

Subscribe to my blog
http://gregorybeamer.spaces.live.com/lists/feed.rss

or just read it:
http://gregorybeamer.spaces.live.com/

*************** *************** **************
| Think outside the box! |
*************** *************** **************
"Marc" <no*****@chello .nlwrote in message
news:%2******** ********@TK2MSF TNGP03.phx.gbl. ..
>Hi, I don't get it I cannot get this to work, can somebody give me a hint
Table1 contains a field Id which is a GUID as primary key and DATA a
string, I want to insert a new row but it does not work.
void gv_RowCommand(O bject sender, GridViewCommand EventArgs e)
{
ClientScript.Re gisterStartupSc ript(GetType(), "MyAlert2",
"alert('Comman d=" + e.CommandName + "');", true);
if (e.CommandName == "New")
{
SqlCommand cmd = new SqlCommand();

//First problem How do I make a GUID?
SqlGuid g = new SqlGuid("3AAAAA AA-BBBB-CCCC-DDDD-2EEEEEEEEEEE");
//Second problem, how do I use the GUID in the Insert
cmd.CommandText = "INSERT INTO dbo.Table1
Values("+g.ToS tring()+",'tst' )"; //?????
cmd.CommandType = CommandType.Tex t ;
SqlConnection sqlConnection1 = new
SqlConnection( SqlDataSource1. ConnectionStrin g);
cmd.Connection = sqlConnection1;
sqlConnection1. Open();
cmd.ExecuteNonQ uery();
sqlConnection1. Close();
GridView1.DataB ind();
}
}

Aug 12 '08 #3
That looks like more of a varchar/string issue, rather than a Guid.

What's the maxlength of your string column in the db?
"Marc" <no*****@chello .nlwrote in message
news:eQ******** ******@TK2MSFTN GP04.phx.gbl...
>I am beginning to loose faith now.... I am getting the message:

String or binary data would be truncated.
The statement has been terminated.

This is the code:

SqlCommand cmd = new SqlCommand();
SqlGuid guid = new SqlGuid(Guid.Ne wGuid());
string str = "some string here";
string sql = "INSERT INTO TABLE1 VALUES (@guid,@str)";
cmd.CommandText = sql;
cmd.Parameters. AddWithValue("@ guid", guid);
cmd.Parameters. AddWithValue("@ str", str);
cmd.CommandType = CommandType.Tex t ;
SqlConnection sqlConnection1 = new
SqlConnection(S qlDataSource1.C onnectionString );
cmd.Connection = sqlConnection1;
sqlConnection1. Open();
cmd.ExecuteNonQ uery();
sqlConnection1. Close();
GridView1.DataB ind();

Server Error in '/H4SP2' Application.
String or binary data would be truncated.
The statement has been terminated.
Description: An unhandled exception occurred during the execution of the
current web request. Please review the stack trace for more information
about the error and where it originated in the code.

Exception Details: System.Data.Sql Client.SqlExcep tion: String or binary
data would be truncated.
The statement has been terminated.

Source Error:

Line 40: cmd.Connection = sqlConnection1;
Line 41: sqlConnection1. Open();
Line 42: cmd.ExecuteNonQ uery();
Line 43: sqlConnection1. Close();
Line 44: GridView1.DataB ind();
Source File: c:\Documents and Settings\Marc wentink\Mijn documenten\Visu al
Studio 2005\WebSites\H 4SP2\Default.as px.cs Line: 42

Stack Trace:

[SqlException (0x80131904): String or binary data would be truncated.
The statement has been terminated.]
System.Data.Sql Client.SqlConne ction.OnError(S qlException exception,
Boolean breakConnection ) +95
System.Data.Sql Client.SqlInter nalConnection.O nError(SqlExcep tion
exception, Boolean breakConnection ) +82

System.Data.Sql Client.TdsParse r.ThrowExceptio nAndWarning(Tds ParserStateObje ct
stateObj) +346
System.Data.Sql Client.TdsParse r.Run(RunBehavi or runBehavior, SqlCommand
cmdHandler, SqlDataReader dataStream, BulkCopySimpleR esultSet
bulkCopyHandler , TdsParserStateO bject stateObj) +3244
System.Data.Sql Client.SqlComma nd.FinishExecut eReader(SqlData Reader ds,
RunBehavior runBehavior, String resetOptionsStr ing) +186
System.Data.Sql Client.SqlComma nd.RunExecuteRe aderTds(Command Behavior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
+1121
System.Data.Sql Client.SqlComma nd.RunExecuteRe ader(CommandBeh avior
cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method,
DbAsyncResult result) +334
System.Data.Sql Client.SqlComma nd.InternalExec uteNonQuery(DbA syncResult
result, String methodName, Boolean sendToPipe) +407
System.Data.Sql Client.SqlComma nd.ExecuteNonQu ery() +149
_Default.gv_Row Command(Object sender, GridViewCommand EventArgs e) in
c:\Documents and Settings\Marc wentink\Mijn documenten\Visu al Studio
2005\WebSites\H 4SP2\Default.as px.cs:42
System.Web.UI.W ebControls.Grid View.OnRowComma nd(GridViewComm andEventArgs
e) +96
System.Web.UI.W ebControls.Grid View.HandleEven t(EventArgs e, Boolean
causesValidatio n, String validationGroup ) +121
System.Web.UI.W ebControls.Grid View.RaisePostB ackEvent(String
eventArgument) +215

System.Web.UI.W ebControls.Grid View.System.Web .UI.IPostBackEv entHandler.Rais ePostBackEvent( String
eventArgument) +31
System.Web.UI.P age.RaisePostBa ckEvent(IPostBa ckEventHandler
sourceControl, String eventArgument) +32
System.Web.UI.P age.RaisePostBa ckEvent(NameVal ueCollection postData) +244
System.Web.UI.P age.ProcessRequ estMain(Boolean
includeStagesBe foreAsyncPoint, Boolean includeStagesAf terAsyncPoint) +3838

Version Information: Microsoft .NET Framework Version:2.0.507 27.42;
ASP.NET Version:2.0.507 27.42
"Cowboy (Gregory A. Beamer)" <No************ @comcast.netNoS pamMschreef
in bericht news:uN******** ******@TK2MSFTN GP06.phx.gbl...
> SqlGuid guid = new SqlGuid(Guid.Ne wGuid());
string str = "some string here";

string sql = "INSERT INTO TABLE VALUES (@guid,@str)";

SqlCommand cmd = new SqlCommand();
cmd.Parameters. AddWithValue("@ guid", guid);
cmd.Parameters. AddWithValue("@ str", str);
--
Gregory A. Beamer
MVP, MCP: +I, SE, SD, DBA

Subscribe to my blog
http://gregorybeamer.spaces.live.com/lists/feed.rss

or just read it:
http://gregorybeamer.spaces.live.com/

************** *************** ***************
| Think outside the box! |
************** *************** ***************
"Marc" <no*****@chello .nlwrote in message
news:%2******* *********@TK2MS FTNGP03.phx.gbl ...
>>Hi, I don't get it I cannot get this to work, can somebody give me a
hint Table1 contains a field Id which is a GUID as primary key and DATA
a string, I want to insert a new row but it does not work.
void gv_RowCommand(O bject sender, GridViewCommand EventArgs e)
{
ClientScript.Re gisterStartupSc ript(GetType(), "MyAlert2",
"alert('Comma nd=" + e.CommandName + "');", true);
if (e.CommandName == "New")
{
SqlCommand cmd = new SqlCommand();

//First problem How do I make a GUID?
SqlGuid g = new SqlGuid("3AAAAA AA-BBBB-CCCC-DDDD-2EEEEEEEEEEE");
//Second problem, how do I use the GUID in the Insert
cmd.CommandText = "INSERT INTO dbo.Table1
Values("+g.To String()+",'tst ')"; //?????
cmd.CommandType = CommandType.Tex t ;
SqlConnection sqlConnection1 = new
SqlConnection (SqlDataSource1 .ConnectionStri ng);
cmd.Connection = sqlConnection1;
sqlConnection1. Open();
cmd.ExecuteNonQ uery();
sqlConnection1. Close();
GridView1.DataB ind();
}
}


Aug 12 '08 #4

"sloan" <sl***@ipass.ne tschreef
What's the maxlength of your string column in the db?
That's it! Works like a charm now. :-)
Aug 12 '08 #5

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

Similar topics

17
57398
by: gokul | last post by:
Hi, Iam a newbie to dotnet and I experience problems in using the Browser control in VB .net. Though Iam able to use it with its basic features, I need to customise it. http://www.codeproject.com/books/0764549146_8.asp The above link shows where what I want is achived in C#, but I need t oa cjhive the same in VB .net. Someone help and guidance would be much appreciated.
0
8375
by: grutta | last post by:
I am writing a windows service that will recieve notification when a USB Device is insterted into the machine. I have used the RegisterDeviceNotification and the RegisterServiceCtrlHandlerEx with a handler. The handler portion seems to fail indicating that my parameters are invalid. I am getting an error code 126 when i try to register the handler and 28 when i register for event notification. Any ideas as to what the deal is? I am...
1
634
by: Henning Kristensen | last post by:
Hi I need a little help with some VB.Net code.. I am pulling my computer's GUID out using WMI Dim wmiObj As New System.Management.ManagementObjectSearcher("SELECT UUID FROM Win32_ComputerSystemProduct" Dim objMgmt As System.Management.ManagementObjec Dim MyByteGuid As Byte( Dim MyStringGuid As Strin Dim MyGuid As Gui For Each objMgmt In wmiObj.Ge
1
2961
by: Wm. Scott Miller | last post by:
I have a Custom DTS Task for SQL Server and I've got it working fine, except for when I try to access its properties from an ActiveX script. I have added a new property called Length and a method called Generate that returns a string. Whenever I get the object in the ActiveX script, the only properties and methods I can use are for the CustomTask interface, not the extended properties I've added. Does anyone know why these properties...
2
7713
by: Anders Borum [.NET/C# MCP] | last post by:
Hello! With C# 2.0 coming up, I was wondering what your thoughts are regarding the introduction of access modifiers on set accessors. Personally, I like the first example, because of its simplicity. The second seems rather dangerous and the third one - well, quite verbose. I'm trying to communicate best practices to fellow developers in-house - and figured some of you already had experience from past projects / languages
0
3179
by: Simon Gregory | last post by:
I'm trying to override the default elementnames in the (seemingly) simple case of serializing an array of GUIDs into XML. Here's the basic code I started with: Dim arrGuids(3) as Guid arrGuids(0) = Guid.NewGuid arrGuids(1) = Guid.NewGuid arrGuids(2) = Guid.NewGuid
5
6340
by: rcolby | last post by:
Evening, Wondering if someone can point me in the right direction, on how I would compare a system.guid with a system.byte. system.guid (pulled from sql server table with a data type of uniqueidentifier, originally taken from objectGUID from active directory domain)
16
9787
by: Asaf | last post by:
I am trying to create and use a COM object with C#.NET 2005. The assembly is set to "Register for COM interop" but when I am trying to call it from VB on Word 2003 I am getting this error: Run-time error '-2147024894 (80070002)': File or assembly name COMTest3, or one of its dependencies, was not found. The code for the COM:
2
8140
by: sk.rasheedfarhan | last post by:
Hi , I have to extract a xml file line by line. Here is my xml Step1: <category name= "name" guid="{guid}"state="enabled"> Step2: <rules> Step3: <rule name="rule name" guid="{guid}" Step4: <\rule> Step5: <\rules> Step6: <\category> So I have to extract, only one step at a single time; I have written a sample code but it was not working properly. So can
0
9423
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
10214
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...
1
9996
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
9865
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8872
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
6674
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
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3963
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2815
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.