有条件地显示或隐藏ASP.NET GridView列

14

这是我如何导航到myPage.aspx页面,

<a href='~/myPage.aspx?show=<%#Eval("id")%>' id="showEach" runat="server">Show Each</a>

<a href="~/myPage.aspx?show=all" id="showAll" runat="server">Show All</a>

而且我在myPage.aspx中有一个网格视图

<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:BoundField  HeaderText="ColumnOne"  Visible="true"/>
<asp:BoundField  HeaderText="ColumnTwo"  Visible="true"/>
</Columns>
</asp:GridView>
我想要做的是,如果查询字符串等于all(~/myPage.aspx?show=all),我想将GridView1的Column2可见性设置为true,否则,设置为false。 我该怎么做?

你如何在GridView中绑定数据?在哪里绑定数据? - Amit Singh
这与我的GridView的数据源无关,AmitSingh,它取决于查询字符串! - zey
这个回答解决了你的问题吗?通过代码隐藏GridView列 - Michael Freidgeim
3个回答

11

您可以使用gridview的预渲染方法来设置此项...

protected void GridView_PreRender(object sender, EventArgs e)
    {
        if(Reqest.QueryString["Id"]=="all"&& Reqest.QueryString["Id"]!=null)
         {
           GridViewId.Columns[1].Visible = true;
         }
        else
            GridViewId.Columns[1].Visible = false;
    }

有没有办法使likes > <asp:BoundField HeaderText="ColumnTwo" Visible='if(Request.QueryString[show])==all){....}else{....}'/> - zey
你应该使用 '==' 而不是 '='。 - शेखर

8
您可以使用GridView列索引来隐藏特定列。
代码示例:
 if(Request.QueryString.Get("show")=="all")
    GridView1.Columns[1].Visible=true;
 else
    GridView1.Columns[1].Visible=false;

更多细节

通过代码隐藏GridView列

编辑3

ASPX / ASCX中的设置不能直接完成。

<%= %> 直接输出到响应流中,而asp标记不是响应流的一部分。假设 <%= %> 运算符在 asp 标记上执行任何预处理是错误的。

更多解释

为什么在服务器控件的属性值中使用<%= %>表达式会导致编译错误?

编辑1

我认为是的

 <asp:BoundField HeaderText="ColumnTwo" 
      Visible='<% if (Request.QueryString.Get("all") == "all" ) "true" else "false" %>'/>

你需要检查语法

编辑2

尝试这个

 Visible='<% Request.QueryString.Get("all") == "all"? "true": "false"%>'

有没有办法使likes > <asp:BoundField HeaderText="ColumnTwo" Visible='if(Request.QueryString[show])==all{....}else{....}'/> - zey
是的,Shekhar,它说“此表达式不是有效语句” :) - zey

1
亲爱的,尝试使用Grid View的RowDataBound事件,例如:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        //here apply your condition
        if(Request.QueryString["name"] == "all")
        e.Row.Cells[<index_of_cell>].Visible = true;
        else
        e.Row.Cells[<index_of_cell>].Visible = false;
    }
}

尝试这样做。

希望它对你有用。


有没有办法使likes > <asp:BoundField HeaderText="ColumnTwo" Visible='if(Request.QueryString[show])==all{....}else{....}'/> - zey
1
你想要绑定数据的方式是可行的,但不能在 BoundField 中实现,必须使用 ItemTemplate。请查看此链接 http://stackoverflow.com/questions/1839163/aspboundfield-view-the-values-with-a-condition ,需要做类似的操作。 - Rahul

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接