具有展开和折叠功能的嵌套 GridView - ASP.NET C#

Nested GridView with Expand and Collapse feature - ASP.NET C#

我在 gridview 内部有一个 Gridview,具有展开和折叠功能。我已经按照 link 来实现这一点。最初 gridview 显示一个加号图标,如果用户点击它,它会变成减号图标并显示嵌套的 gridview。现在,如果嵌套 gridview.And 中没有数据,我想将初始图标设置为减号,单击此减号图标时不会发生任何事情。如果嵌套的 gridview 上有数据,它的行为应该和现在一样正常。

<asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" CssClass="Grid"
DataKeyNames="CustomerID" OnRowDataBound="OnRowDataBound">
<Columns>
    <asp:TemplateField>
        <ItemTemplate>
            <img alt = "" style="cursor: pointer" src="images/plus.png" />
            <asp:Panel ID="pnlOrders" runat="server" Style="display: none">
            <div class="userGrid">
                <asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass = "ChildGrid">
                    <Columns>
                        <asp:BoundField ItemStyle-Width="150px" DataField="OrderId" HeaderText="Order Id" />
                        <asp:BoundField ItemStyle-Width="150px" DataField="OrderDate" HeaderText="Date" />
                    </Columns>
                </asp:GridView>
             </div>
            </asp:Panel>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" />
    <asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />
</Columns>

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
 <script type="text/javascript">
    $("[src*=plus]").live("click", function () {
    $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
    $(this).attr("src", "images/minus.png");
});
$("[src*=minus]").live("click", function () {
    $(this).attr("src", "images/plus.png");
    $(this).closest("tr").next().remove();
});
   $(document).ready(function () {
        $("#<%=gvCustomers.ClientID %> tr").each(function () {
            if ($(this).find('.userGrid table tr').length > 0) {
            //need to set plus icon  
                alert("Yes,gvOrders has row");
           } else {
                //need to set minus icon without click event
                alert("no,gvOrders has no  row");
           }
       });//end of loop

   });
  </script>

您已经有一个 RowDataBound 事件。为什么不用图像控件替换图像。

<asp:Image ID="Image1" runat="server" ImageUrl="images/plus.png" />

然后您可以检查嵌套的GridView是否有任何数据并相应地更改ImageUrl。然后你也可以很容易地确保图像有一个指针光标,如果它可以扩展。

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Image img = e.Row.FindControl("Image1") as Image;

        if (nestedSource == 0) {
            img.ImageUrl = "images/min.png";
        }
        else
        {
            img.Attributes.Add("style", "cursor:pointer");
        }
    }
}