我有一个GridView I填充,并希望根据登录的用户是管理员还是用户来显示/隐藏编辑链接。我没有收到任何错误,但无法弄清楚为什么它不起作用。
ASPX
<asp:GridView ID="RepView" runat="server" HeaderStyle-BackColor="#bfbfbf" HeaderStyle-ForeColor="White" HeaderStyle-Font-Underline="true" CellPadding="2" GridLines="None" AutoGenerateColumns="false" Width="990px">
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="EmployeeId" HeaderText="Employee Id" />
<asp:BoundField DataField="Shift" HeaderText="Shift" />
<asp:BoundField DataField="Supervisor" HeaderText="Supervisor" />
<asp:BoundField DataField="Center" HeaderText="Center" />
<asp:BoundField DataField="DateSubmitted" HeaderText="Date Entered" />
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Details">
<ItemTemplate>
<a href="/Admin/Details.aspx?AssignmentID=<%# Eval("Id") %>">Edit</a>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
代码
Private Sub BindGrid()
Dim DefaultConnection As String = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
Using con As New SqlConnection(DefaultConnection)
'This is not working...
If My.User.IsInRole("User") Then
RepView.Columns(9).Visible = False
ElseIf My.User.IsInRole("Admin") Then
RepView.Columns(9).Visible = True
End If
' End of questionable part....
Using cmd As New SqlCommand()
cmd.CommandText = ("SELECT * from Reps")
cmd.Connection = con
con.Open()
RepView.DataSource = cmd.ExecuteReader()
RepView.DataBind()
con.Close()
End Using
End Using
End Sub
答案 0 :(得分:0)
尝试将“可疑部分”后面的代码从Private Sub BindGrid()移动到gridview_Load事件。我的猜测是发生了什么是gridview正在加载,然后它到你的代码私有子BindGrid()来显示/隐藏列,但列已经加载,因此它无法隐藏它们。除非您运行检查并在加载事件中显示/隐藏列,否则它将在运行此代码后继续显示列。
另一个可能的解决方案是,在Private Sub BindGrid()中,您试图在查询之前隐藏列,这意味着尚未创建列,因此您必须先创建列,然后才能隐藏他们。将可疑部分向下移动到sql命令下面。
尝试这样的事情......
Protected Sub GridView1_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
Dim x As Integer = 0
If x = 0 Then
GridView1.Columns(0).Visible = False
Else
GridView1.Columns(0).Visible = True
End If
End Sub
我测试了这个并使用x = 0将使用x = 1隐藏第一列将显示第一列。
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ID" DataSourceID="SqlDataSource1">
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Sprayer_Parts_CatalogConnectionString %>"
SelectCommand="SELECT [ID], [Order#] AS column1, [Gallon], [Price] FROM [Tanks]">
</asp:SqlDataSource>