[英]Invalid cast from 'System.String' to 'System.Guid'
[英]Invalid cast from 'System.String' to 'System.Guid
我的頁面使用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的Text Field上調用ToString
,因為它已經是string類型的。
(請記住,.net Framework 4.0及更高版本支持Guid.Parse )
如果從TextBox
獲取輸入,則在這種情況下,您可能會遇到Guid
無效值,則可以使用Guid.TryParse
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.