在asp.net gridview中显示父/子记录

时间:2011-11-09 19:34:47

标签: asp.net sql gridview parent-child

好吧我似乎无法想出这一个..我有1个表有列id,parentid 这允许选项具有子选项。所以它会是这样的:

id  |  parentid
1   |    null
2   |    null
3   |      1 

我需要在gridview中显示它是这样的:

id  |  parentid
 1  |     null
 3  |      1
 2  |     null

任何想法我都会非常高兴......以防万一我在搜索时尝试过Sql COALESCE,但这也没有用..

1 个答案:

答案 0 :(得分:0)

我会使用ListView或DataList而不是GridView。这应该会让你走上正确的道路:

<table width="595px">
    <asp:DataList BackColor="#ffffff" id="DataList1" DataKeyField="<ID>" OnItemDataBound="DataList1_ItemDataBound" runat="server" Width="100%">     
        <ItemTemplate>
           <tr>
              <td>
                  <asp:LinkButton ID="LinkButton1" runat="server" Text="+" OnCommand="LinkButton1_Command" CommandArgument='<%#Container.ItemIndex%>'></asp:LinkButton>    
              </td>
              <td><%#Eval("<COLUMN NAME>")%></td>
              <td><%#Eval("<COLUMN NAME>")%></td>
              <td><%#Eval("<COLUMN NAME>")%></td>
           </tr>
           <asp:PlaceHolder ID="plcChildView" runat="server">
               <asp:DataList ID="DataList2" runat="server" Width="100%">
                   <ItemTemplate>
                       <tr>
                          <td><%#Eval("<CHILD OLUMN NAME>")%></td>
                          <td><%#Eval("<CHILD COLUMN NAME>")%></</td>
                          <td><%#Eval("<CHILD COLUMN NAME>")%></</td>                           
                       </tr>
                   </ItemTemplate>
               </asp:DataList>
           </asp:Panel>
        </ItemTemplate>
    </asp:DataList>
</table>

当用户单击DataList1中的LinkBut​​ton / Button时,请执行以下操作:

protected void LinkButton1_Command(object sender, CommandEventArgs e)
{
    //pass index of item in command argument
    int itemIndex = Convert.ToInt32(e.CommandArgument);      

    //find the pnlChildView control
    PlaceHolder childViewHolder = (PlaceHolder)DataList1.Items[itemIndex].FindControl("plcChildView");
    if (childViewHolder != null)
    {
        //toggle visibility of childViewPanel and bind child list if panel is visible

        if (childViewHolder.Visible)
        {
            DataList childList = childViewHolder.FindControl("DataList2");
            if (childList != null)
            {
                int keyValue = (int)DataList1.DataKeys[itemIndex];

                //bind the list using DataList1 data key value
                childList.DataSource = <DATA SOURCE>; //get data using keyValue
                childList.DataBind();
            }  
        }
    }
}