tags:

views:

70

answers:

2

I am trying to compare a session variable to another string so that i can enable or disable image buttons. i am using asp.net vb with a sql2005 express backend

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    Dim string1 As String
    Dim string2 As String

    Label1.Text = Session("Username")
    Label2.Text = Session("UserId")

    string1 = Session("Username")
    string2 = "medev"

    If String.Compare(string1, string2, True) = 1 Then
        ImageButton1.Enabled = False

    End If
+1  A: 

String.Compare returns -1, 0 or 1 depending on the result:

String.Compare("A", "B", true) ' returns -1 '
String.Compare("B", "A", true) ' returns 1 '
String.Compare("B", "B", true) ' returns 0 '

In your case, ImageButton1 will be disabled if the user name would come before "medev" if you sorted them as a list. So "Adam" wound have it disabled, while "Stuart" would have it enabled. "medev" would also get it disabled, because if the strings are equal, String.Compare returns 0. My guess is that you want ImageList1 enabled for "medev":

If String.Compare(string1, string2, True) <> 0 Then
    ImageButton1.Enabled = False
End If

I would also suggest using the String.Compare overload that takes a StringComparison instead of a bool to get a case insensitive compare. In my opinion it makes it a lot easier to understand what the code does:

If String.Compare(string1, string2, StringComparison.InvariantCultureIgnoreCase) <> 0 Then
    ImageButton1.Enabled = False
End If
Fredrik Mörk
A: 

this is works!

    ImageButton1.Enabled = Not Session("UserName") Is Nothing AndAlso Session("UserName").ToString.ToLower.Trim.Equals("username")

ImageButton2.Enabled = Not Session("UserName") Is Nothing AndAlso_ Session("UserName").ToString.ToLower.Trim.Equals("username")