Reputation: 63
My page uses a GridView to show all clients to the user after he or she logs in. However I'm trying to get the GridView to show only those clients that belong to the respective user.
...the code behind:
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();
...the stored procedure:
ALTER PROCEDURE dbo.getClients
@UserId uniqueidentifier
AS
BEGIN
SELECT ClientId, UserId, ClientName, EmailAddress, PhoneNumber, ServicesNum
FROM Client_tb
WHERE UserId = @UserId
END
when I run the page, I get the error: Invalid cast from 'System.String' to 'System.Guid ...could I get some help with this please?
Upvotes: 1
Views: 18099
Reputation: 223267
You need to parse the string guid to Guid
like:
cmd.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier).Value = Guid.Parse(txtUserId.Text);
You can also pass the string
value in a Guid
constructor like:
cmd.Parameters.Add("@UserId", SqlDbType.UniqueIdentifier).Value = new Guid(txtUserId.Text);
Also there is no need to call ToString
on TextBox's Text Field, it is already of type string.
(Remember Guid.Parse is supported in .Net framework 4.0 and higher)
If you are getting the input from a TextBox
then chances are you might encounter invalid values for the Guid
in that case you can use Guid.TryParse
method.
Upvotes: 5