2013-02-13 51 views
0

我有一個用戶控件這樣一個超級簡單的GridView設置內:其綁定到一個GridView是一個用戶控件

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

我註冊的用戶控制像這樣:

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

我問題是,我無法弄清楚如何在使用用戶控件的.aspx頁面中進行數據綁定。

我試着這樣做:

test1a.gvTestUC 

但它無法找到GridView的。

我試圖從.aspx頁面數據綁定gridview的原因是因爲所有需要此用戶控件的頁面都需要將不同的數據綁定到其內部的gridview。

任何幫助,將不勝感激。

謝謝!

+1

難道你不能使用test1a.FindControl(「gvTestUC」)找到文章,然後找到DataBind? – 2013-02-13 15:45:23

回答

3

你只需要提供一個公共的方法,你可以從你的頁面調用。

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 
Page

當你想它數據綁定:

test1a.BindData(GetGridDataSource()) 

側面說明:永遠不要讓一個UserControl數據綁定本身Page_Load。這可能會導致令人討厭的副作用,從控制器的頁面中移除控件,並且會阻止在需要時延遲加載控件(在TabIndexChanging上使用TabContainer控件)。

+0

但是這是獲取用戶控件中的數據源。我在我的頁面中填充數據集,然後我需要使用該數據集來綁定用戶控件gridview。謝謝 – SkyeBoniwell 2013-02-13 15:50:02

+1

@ 999cm999:然後提供一個公共屬性'DataSource'或者 - 更好 - 將它作爲參數傳遞給方法。我會編輯我的答案。 – 2013-02-13 15:53:08

+0

真棒例子...謝謝 – SkyeBoniwell 2013-02-13 15:59:49

相關問題