Reputation: 7092
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!
Upvotes: 0
Views: 4008
Reputation: 460128
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 (f.e. on TabIndexChanging with a TabContainer
control).
Upvotes: 3