How to hide randomly generated row of gridview

你。 提交于 2019-11-29 17:30:33
rusmus

Can't you just do this with css?

table tr:nth-child(n + 3) {
    display: none;
}

There is an explanation of the nth-child css-selector here:

http://css-tricks.com/how-nth-child-works/

I've also explained it in another answer here:

https://stackoverflow.com/a/21166162/1256868

You would probably need a class or a static id on the generated table so you can single that table out, but still...

Edit following comments:

Try adding a css class to the gridview and adding the css above like this:

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        table.Grid tr:nth-child(n + 3) {
            display: none;
        }
    </style>
</head>
<body>
    <form runat="server">
    <asp:GridView runat="server" CssClass="Grid">
        <%--Your templates here--%>
    </asp:GridView>
    </form>
</body>
</html>

Asp.net will generate an html table from your gridview, that is why you need to apply styling to a table. The browser never sees any asp.net code. That code is simply a way of generating html that the browser knows how to display.

Edit regarding better IE support:

I guess what you are asking is for IE8 (and possibly 7) support, as IE9 and up support nth-child. To support IE7 and up, change your css to use the + selector, which has better support:

table.Grid tr + tr + tr{    
    display: none;
}

The + selector is the adjacent sibling selector. The selector tr + tr thus selects any tr that immediatly follows another tr element. For further exaplnation see: http://css-tricks.com/child-and-sibling-selectors/ (specifically the section titled 'Adjacent sibling combinator').

I think it's what you are looking for :

for(int i = 1; i < GridView1.Rows.Count; i++)
{
    GridView1.Rows[i].Visible = false;
}

Use it after binding datasource to GridView1 in code behind.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!