我有一个DetailsView,我需要在DataKeyNames"UserId"(一个Guid字段)中获取值,并将其添加到Object Guid.
目前我正在使用此代码:
String myUserId = (String)uxAuthorListDetailsView.DataKey["UserId"].ToString();
Run Code Online (Sandbox Code Playgroud)
但我需要这样的东西:
Guid myUserGuid = (Guid)uxAuthorListDetailsView.DataKey["UserId"].ToString();
Run Code Online (Sandbox Code Playgroud)
但是不起作用我得到错误错误
Cannot convert type 'string' to 'System.Guid'
Run Code Online (Sandbox Code Playgroud)
可能是什么问题呢?谢谢你们的支持!
好吧,问题是你正在调用ToString()然后尝试将该字符串转换为a Guid,当没有可用的转换时.可能的选择:
演员代替的调用ToString(),如果原始值实际上是一个GUID:
Guid guid = (Guid)uxAuthorListDetailsView.DataKey["UserId"];
Run Code Online (Sandbox Code Playgroud)解析字符串:
Guid guid = new Guid(uxAuthorListDetailsView.DataKey["UserId"].ToString());
Run Code Online (Sandbox Code Playgroud)If this is user-entered data at all, or there's any other reason why the value is half-expected to be incorrect, and if you're using .NET 4, you might want to use Guid.TryParse instead, which will allow you to handle failure without an exception.