Gridview中的DataBind用户控件

时间:2011-01-26 11:00:51

标签: c# asp.net user-controls dynamic data-binding

我在ASP.Net中有一个GridView,其中放置了一个用户控件:

<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>

我将GridView绑定到一个填充了自定义“单元”类的List<T>。每个单元由几个属性组成,以填充用户控件。 (用户控件包含一个表,以及一些标签和文本框)。 我怎样才能做到这一点?有没有一种简单的方法将每个usercontrol绑定到适当的Unit?

顺便说一句,这是我模仿页面上多个用户控件的“动态”行为的方法。如果有更简单的方法,我想知道如何!

谢谢你!

2 个答案:

答案 0 :(得分:2)

您应该处理OnRowDataBound事件,然后在事件参数上使用FindControl和DataItem属性来提取您绑定的数据。您应该在用户控件上公开属性以指定值。这是一个例子:

<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();
    }
}

您应该强制转换为特定的数据类型而不是标签,而不是转换为您应该转换为您的用户控件类型。您应该使用您的用户控件公开的属性来代替Label的Text属性。

答案 1 :(得分:0)

您可以在usercontrol上创建公共属性,并在gridview的OnRowDataBound事件中为它们分配值。

我的帖子概述了我如何处理动态用户控件here

希望有所帮助!

相关问题