简体   繁体   中英

databind a gridview that is inside a user control

I have a super simple gridview setup in a user control like this:

    <asp:GridView ID="gvTestUC" runat="server" AutoGenerateColumns="false">
        <Columns>
            <asp:BoundField DataField="FirstName" HeaderText="First Name" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" />
            <asp:BoundField DataField="LastName" HeaderText="Last Name" />
            <asp:BoundField DataField="EmailAddress" HeaderText="Email Address" HeaderStyle-HorizontalAlign="Left" ItemStyle-HorizontalAlign="Left" />
        </Columns>
</asp:GridView>

I am registering the user control like this:

<%@ Register src="Controls/test1.ascx" tagname="test1" tagprefix="test1uc" %>
<test1uc:test1 ID="test1a" runat="server" />

My problem is, is that I can't figure out how to databind it in the .aspx page that is using the user control.

I tried doing:

test1a.gvTestUC

But it can't find the gridview.

The reason I am trying to databind the gridview from the .aspx page, is because all the pages that need this user control, will need to bind different data to the gridview that is inside it.

Any help would be appreciated.

Thanks!

You just have to provide a public method which you can call from your page.

in your UserControl :

Public Sub BindData(gridSource As ComponentModel.IListSource)
    BindGridView(dataSource)
End Sub

Private Sub BindGridView(gridSource As ComponentModel.IListSource)
    gvTestUC.DataSource = gridSource 
    gvTestUC.DataBind()
End Sub

in your Page when you want to databind it:

test1a.BindData(GetGridDataSource())

Side-note: never let a UserControl databind itself from Page_Load . This can cause nasty side-effects, removes control from the page which is meant to be the controller and will prevent lazy-loading your control when you want (fe on TabIndexChanging with a TabContainer control).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM