Joris
Joris

Reputation: 741

DataBind User Controls in Gridview

I got a GridView in ASP.Net in which a user control is placed:

<asp:GridView ID="GVWunitcollection"
        CssClass="gridview"
        runat="server"
        ShowHeader="false"
        ShowFooter="false"
        AutoGenerateColumns="False">
        <HeaderStyle CssClass="headerstyle" />
        <RowStyle CssClass="rowstyle row" />
        <FooterStyle CssClass="rowstyle row" />
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <uc:Unit ID="UNTcol" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
</asp:GridView>

I bind the GridView to a List<T> filled with custom 'Unit' Classes. Each Unit consists of several properties to fill the usercontrol. (The user control holds a table, and some labels and textboxes). How can I achieve this? Is there a simple way to bind each usercontrol to the appropriate Unit?

By the way, this is my way to mimic a "dynamic" behavior of multiple usercontrols on a page. If there's a more simple way, I would like to know how!

thank you!

Upvotes: 2

Views: 4205

Answers (2)

Stilgar
Stilgar

Reputation: 23551

You should handle the OnRowDataBound event then use FindControl and the DataItem property on the event argument to extract the data you are binding to. You should expose properties on the user control to assign values to. Here is an example:

<asp:GridView ID="gvTest" runat="server" EnableViewState="false" 
OnRowDataBound="gvTest_RowDataBound" AutoGenerateColumns="false">
<Columns>
    <asp:TemplateField>
        <ItemTemplate>
            <asp:Label ID="lblTest" runat="server"></asp:Label>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>


protected void Page_Load(object sender, EventArgs e)
{
    gvTest.DataSource = new[] { 1, 2, 3, 4 };
    gvTest.DataBind();
}

protected void gvTest_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        int item = (int)e.Row.DataItem;
        Label lblTest = (Label)e.Row.FindControl("lblTest");
        lblTest.Text = item.ToString();
    }
}

Instead of int you should cast to your specific datatype and instead of Label you should cast to your user control type. Instead of the Label's Text property you should assing to the property you've exposed from your user control.

Upvotes: 2

Cognitronic
Cognitronic

Reputation: 1436

You could create public properties on your usercontrol and assign them values in the gridview's OnRowDataBound event.

I have a post that outlines how I handle dynamic usercontrols here

Hope that helps!

Upvotes: 0

Related Questions