Ciaran Gallagher
Ciaran Gallagher

Reputation: 4020

Nesting a ListView inside a GridView

I have an ASP.NET GridView which amongst other values binds an ID to one of the columns.

Another one of the columns of this table should contain a list of items, which should be resolved by passing in the ID from the GridView.

To achieve this, I tried nesting the ListView inside the GridView, and passing the ID into the Default Parameter of an ObjectDataSource used by the ListView, but this syntax is not allowed:

    <asp:TemplateField HeaderText="columnItems">
        <ItemTemplate>
            <asp:ListView ID="listOfItems" runat="server" DataSourceID="MyObjectDataSource >
                <ItemTemplate>
                    <asp:LinkButton ID="MyLinkButton" Runat="Server" Text='item'></asp:LinkButton>
                </ItemTemplate>
            </asp:ListView>
            <asp:ObjectDataSource ID="MyObjectDataSource" runat="server"   
                TypeName="MyTypeName.Whatever" SelectMethod="GetItems">
                <SelectParameters>
                    <asp:Parameter Name="requestId" Type="String" DefaultValue='<%# Eval("ID")'/>
                </SelectParameters>
            </asp:ObjectDataSource>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

So how do I go about passing in the ID so I can get the list of items?

Upvotes: 0

Views: 1958

Answers (2)

Ciaran Gallagher
Ciaran Gallagher

Reputation: 4020

Attach a 'OnRowDataBound' event to the GridView control to retrieve the items for the ListView for each row on the GridView (after the GridView has been bound):

e.g. On the ASPX page:

<asp:GridView id="MyGridView" OnRowDataBound="GetItems" ... > ... </asp:GridView>

In the code-behind:

protected void GetItems(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType != DataControlRowType.DataRow)
    {
        return;
    }

    // Get the ID from the GridView
    var dataRowView = (DataRowView) e.Row.DataItem;
    var id = dataRowView["ID"].ToString();

    // Bind the supporting documents to the ListView control
    var listView = (ListView) e.Row.FindControl("listOfItems");
    listView.DataSource = /* Call to database to return a DataSet of items */;
    listView.DataBind();
}

(As would be appropriate, I tried editing Tunisiano's post to elaborate on his answer on attaching the event to the GridView and getting the request ID, but SO editors are rejecting it for no good reason. The above code is tested and answers the question exactly).

Upvotes: 0

Tunisiano32
Tunisiano32

Reputation: 180

You probably need to do that in the RowDataBound event, get the ID there and then do you DB then do something like

if(e.Row.RowType != DataControlRowType.DataRow)
{
    return;
}

ListView a = (ListView)e.Row.FindControl("listOfItems");
a.datasource = // the result of your db call
a.databind();

Upvotes: 2

Related Questions