[英]How to access dataset defined in master page from user control on master page?
我有一個母版頁,其中包含在 VB 代碼中定義的數據集。
Public Property Inventory As DataSet = New DataSet
我在Page_Init
中填充數據。
我在同一個母版頁上有一個用戶控件。 如何從Page_Load
中的用戶控件代碼 ( myusercontrol.ascx ) 訪問數據集? 我對內容頁面上的用戶控件執行此操作沒有問題,但是當控件位於母版頁上時,我無法使其工作。
通常,我只是將其稱為Master.Inventory
。 當控件位於內容頁面上時,它可以工作,但是當控件位於母版頁上時,我該怎么做呢? 我試過Parent.Page.Master.Inventory
, Page.Master.Inventory
,甚至只是Inventory
。 我得到“未定義庫存”或“庫存不是...的成員”。
在用戶控件中,我只是想做一些像Dim i As DataSet = [reference goes here]
這樣的事情。
首先,在您的母版頁中創建一個公共屬性。 在這種情況下myDataSet
public partial class Site : System.Web.UI.MasterPage
{
public DataTable myDataSet { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
//add some dummy data to the dataset
myDataSet = new DataTable();
myDataSet.Columns.Add("ID", typeof(int));
myDataSet.Columns.Add("COUNTRY", typeof(string));
myDataSet.Rows.Add(0, "Netherlands");
myDataSet.Rows.Add(1, "Japan");
myDataSet.Rows.Add(2, "Country");
}
}
然后在控件的 Page_Load 中對 Master 進行引用,然后您就可以訪問該屬性。
public partial class WebUserControl1 : System.Web.UI.UserControl
{
public Site master;
protected void Page_Load(object sender, EventArgs e)
{
//get the current master page
master = (Site)Page.Master;
//access the public property in the master
Label1.Text = master.myDataSet.Rows[0][1].ToString();
}
}
VB
我為 VB 使用了代碼翻譯器,所以它可能不完全正確。 但你會明白的。
Public Class Site
Inherits System.Web.UI.MasterPage
Public Property myDataSet As DataTable
Get
End Get
Set
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'add some dummy data to the dataset
Me.myDataSet = New DataTable
Me.myDataSet.Columns.Add("ID", GetType(System.Int32))
Me.myDataSet.Columns.Add("COUNTRY", GetType(System.String))
Me.myDataSet.Rows.Add(0, "Netherlands")
Me.myDataSet.Rows.Add(1, "Japan")
Me.myDataSet.Rows.Add(2, "Country")
End Sub
End Class
控制
Public Class WebUserControl1
Inherits System.Web.UI.UserControl
Public master As Site
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
'get the current master page
Me.master = CType(Page.Master,Site)
'access the public property in the master
Label1.Text = Me.master.myDataSet.Rows(0)(1).ToString
End Sub
End Class
我最終走了一條不同的路線。 我直接從母版頁完成了所有操作。
我在我的用戶控件中放置了一個數據綁定控件(我的恰好是一個DropDownList
)。
然后,我向用戶控件myusercontrol.ascx.vb添加了一個DataBind成員。
Public Class MyUserControl
Inherits System.Web.UI.UserControl
Public Property DataSource As DataTable
Get
Return MyDataBoundControl.DataSource
End Get
Set(ByVal _source As DataTable)
MyDataBoundControl.DataSource = _source
End Set
End Property
Public Sub DataBind
MyDataBoundControl.DataBind()
End Sub
End Class
然后在母版頁site.master上:
<MyPrefix:MyUserControl id="MyUserControl" runat="server" />
在site.master.vb后面的母版頁代碼中:
Dim DS As DataTable
[do some stuff to define and populate DS]
MyUserControl.DataSource = DS
MyUserControl.DataBind()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.