2014-02-24 82 views
1

有我一個下拉列表選擇,選擇的值將是ID,類型是GUID,目前我的選擇按鈕的代碼是可能將字符串轉換爲GUID?

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click 

    Dim Selection As String = Nothing 

    If Not DropDownList3.SelectedValue Is Nothing Then Selection = DropDownList3.SelectedValue 

    Session("Selected") = Selection 

End Sub 

然後我有

Dim ID is guid 
ID = Session("Selected") 

然後我需要執行sql這樣作爲select * from .. where ID=.. 問題發生在ID = Session("Selected"),因爲IDGUID,而Session("Selected")string 我不知道是否有辦法處理它? 非常感謝您的幫助!

+0

可能重複的[C#:測試如果字符串是一個GUID沒有拋出異常?](http://stackoverflow.com/questions/104850/c-test-if-string-is-a-guid-without-throwing - 異常) – TFD

回答

3

試試這個方法:

GUID myGuid; 
object myObj = Session("Selected"); 

if (myObj != null && Guid.TryParse(myObj.ToString(), out myGuid)) 
{ 
    //input is good, do stuff here 
} 
else 
{ 
    //input is bad, handle error 
} 

我希望這有助於。祝你好運。

+0

我試過ID = Guid.Parse(Session(「Selected」)),但是當調試有錯誤時說Value不能爲null。 參數名稱:輸入? – user3344443

+0

第一次檢查會話對象是否爲空。如果它爲空,則必須檢查設置它的方法。 – kryptonkal

+0

我猜默認值爲空?開始時沒有在下拉列表中選擇。我猜如果我將ID設置爲GUID類型,那麼我必須爲dropdownlist設置非空默認值? – user3344443