从“System.String”到“System.Guid”的转换无效

Ant*_*ght 1 c# asp.net gridview

我的页面使用 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(); 
Run Code Online (Sandbox Code Playgroud)

...存储过程:

ALTER PROCEDURE dbo.getClients
@UserId uniqueidentifier
AS
BEGIN
    SELECT ClientId, UserId, ClientName, EmailAddress, PhoneNumber, ServicesNum 
    FROM  Client_tb 
    WHERE UserId = @UserId  

END
Run Code Online (Sandbox Code Playgroud)

当我运行该页面时,出现错误:从“System.String”到“System.Guid”的转换无效...我可以获得一些帮助吗?

Hab*_*bib 5

您需要将字符串 guid 解析为Guid

cmd.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier).Value = Guid.Parse(txtUserId.Text);
Run Code Online (Sandbox Code Playgroud)

您还可以stringGuid构造函数中传递值,例如:

cmd.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier).Value = new Guid(txtUserId.Text);
Run Code Online (Sandbox Code Playgroud)

也不需要调用ToStringTextBox 的文本字段,它已经是字符串类型了。

(请记住,.Net Framework 4.0 及更高版本支持Guid.Parse )

如果您从 a 获取输入,TextBox那么您可能会遇到无效的值,Guid在这种情况下您可以使用Guid.TryParse方法。