来自';的无效强制转换;System.String';到';System.Guid
本文关键字:System String Guid 转换 无效 来自 | 更新日期: 2023-09-27 18:27:24
我的页面在用户登录后使用GridView向用户显示所有客户端。然而,我正试图让GridView只显示属于相应用户的客户端。
背后的代码:
String strConnString = ConfigurationManager
.ConnectionStrings["BA_2013ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "getClients";
cmd.Parameters
.Add("@UserId", SqlDbType.UniqueIdentifier)
.Value = txtUserId.Text.ToString();
cmd.Connection = con;
con.Open();
gvClients.DataSource = cmd.ExecuteReader();
gvClients.DataBind();
con.Close();
con.Dispose();
存储过程:
ALTER PROCEDURE dbo.getClients
@UserId uniqueidentifier
AS
BEGIN
SELECT ClientId, UserId, ClientName, EmailAddress, PhoneNumber, ServicesNum
FROM Client_tb
WHERE UserId = @UserId
END
当我运行该页时,我得到错误:从"System.String"到"System.Guid"的强制转换无效…能帮我一下吗?
您需要将字符串guid解析为Guid
,如:
cmd.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier).Value = Guid.Parse(txtUserId.Text);
您也可以在Guid
构造函数中传递string
值,如:
cmd.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier).Value = new Guid(txtUserId.Text);
此外,不需要在TextBox的文本字段上调用ToString
,它已经是字符串类型了。
(记住Guid.Parse在.Net framework 4.0及更高版本中受支持)
如果您从TextBox
获得输入,那么您可能会遇到Guid
的无效值,在这种情况下,您可以使用Guid.TryParse
方法。