开发者

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!


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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜