asp.netimagebuttondirectcast

Image Button does not hide on page load


I used code below to hide template field Imagebutton on pageload but it DOES NOT work, Thanks in advance:

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
            Dim ImageButton1 As ImageButton = DirectCast(GridView1.FindControl("ImageButton1"), ImageButton)
            If User.Identity.Name.Substring(InStr(User.Identity.Name, "\")).ToUpper = "User1" Then
                ImageButton1.Visible = False
            End If
        End Sub

Solution

  • Assuming you have binding grid before and it has rows. Find the ImageButton in some row of grid instead of find within gridview. The if condition you have seems to never get true, as you are comparing string after ToUpper with a string that is not in upper case, Change User1 to USER1 As you are using ToUpper.

    Change

     Dim ImageButton1 As ImageButton = DirectCast(GridView1.FindControl("ImageButton1"), ImageButton) 
     If User.Identity.Name.Substring(InStr(User.Identity.Name, "\")).ToUpper = "User1" Then
                ImageButton1.Visible = False
     End If
    

    To

       Dim ImageButton1 As ImageButton = DirectCast(GridView1.Rows(0).FindControl("ImageButton1"), ImageButton)
     If User.Identity.Name.Substring(InStr(User.Identity.Name, "\")).ToUpper = "USER1" Then
           ImageButton1.Visible = False
     End If
    

    Iterating whole grid by loop

    For Each row As GridViewRow In GridView1.Rows
     Dim ImageButton1 As ImageButton = DirectCast(row.FindControl("ImageButton1"), ImageButton)
         If User.Identity.Name.Substring(InStr(User.Identity.Name, "\")).ToUpper = "USER1" Then
               ImageButton1.Visible = False
         End If
    Next