Reputation: 73918
I need cast a String
to a Guid
.
I am using this code but
string myUserIdContent = ((Label)row.FindControl("uxUserIdDisplayer")).Text;
Guid myGuidUserId = new Guid(myUserIdContent); // PROBLEM HERE
MembershipUser mySelectedUser = Membership.GetUser(myGuidUserId);
I receive this error
Exception Details: System.FormatException: Unrecognized Guid format.
What is the proper way to achieve the results?
Upvotes: 3
Views: 8388
Reputation: 26853
By the looks of that exception, your string isn't correctly formatted. Per MSDN:
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}}
All braces, commas, and "0x" prefixes are required. All embedded spaces are ignored. All leading zeros in a group are ignored.
The digits shown in a group are the maximum number of meaningful digits that can appear in that group. You can specify from 1 to the number of digits shown for a group. The specified digits are assumed to be the low-order digits of the group.
Upvotes: 2
Reputation: 49261
Use Guid.TryParse.
string myUserIdContent = ((Label)row.FindControl("uxUserIdDisplayer")).Text;
Guid myGuidUserId;
if (Guid.TryParse(myUserIdContent, out myGuidUserId)
{
MembershipUser mySelectedUser = Membership.GetUser(myGuidUserId);
}
else
{
// throw exception and/or inform user
}
Upvotes: 6