Is there any built-in method in asp.net to convert a string to a uniqueidentifier
for SQL Server, just like .ToString()
.
I get an error: Conversion failed when converting from a character string to uniqueidentifier.
Or does anyone have an idea how to do solve this problem. Thanks.
There's a constructor for Guid
which takes a string
as a parameter.
Guid aGuid = new Guid(aString);
Make sure it's in the correct format:
A string that contains a GUID in one of the following formats ("d" represents a hexadecimal digit whose case is ignored):
32 contiguous digits: dddddddddddddddddddddddddddddddd
-or-
Groups of 8, 4, 4, 4, and 12 digits with hyphens between the groups. The entire GUID can optionally be enclosed in matching braces or parentheses: dddddddd-dddd-dddd-dddd-dddddddddddd -or- {dddddddd-dddd-dddd-dddd-dddddddddddd} -or- (dddddddd-dddd-dddd-dddd-dddddddddddd)
-or-
Groups of 8, 4, and 4 digits, and a subset of eight groups of 2 digits, with each group prefixed by "0x" or "0X", and separated by commas. The entire GUID, as well as the subset, is enclosed in matching braces: {0xdddddddd, 0xdddd, 0xdddd,{0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd,0xdd}}
Full documentation can be found here.
You can pass your RoleID guid in as a parameter:
Guid roleID = new Guid(roleIDAsString);
sqlCommand.Parameters.Add("@RoleID", SqlDbType.UniqueIdentifier).Value = roleID;
Guid outGuid;
Guid.TryParse(stringInput, out outGuid);
Won't crash if the string is incorrectly formatted
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With