我在ASP.NET(VB)中有一个简单的UserControl,其中包含以下代码页:
ASCX:
<%@ Control Language="VB" AutoEventWireup="false" CodeFile="DistPOLine.ascx.vb" Inherits="DistPOLine" %>
<asp:Label ID="lbDistSKU" runat="server" Text="Label"></asp:Label>
ASCX.VB
Partial Class DistPOLine
Inherits System.Web.UI.UserControl
Public Property DistSKU As String
Get
DistSKU = lbDistSKU.Text
End Get
Set(value As String)
lbDistSKU.Text = value
End Set
End Property
End Class
如果我直接在aspx页面中引用控件,我可以设置其DistSKU属性而不会出现问题。
<%@ Register src="DistPOLine.ascx" tagname="POline" tagprefix="POL" %>
<POL:POline ID="POline1" DistSKu="test Here" runat="server" /><br />
但在我的代码背后,我在循环中创建用户控件,我无法直接访问属性,即使使用FindControl并将控件转换为标签。控件已创建,但我需要在创建后操作它们。 (我已经简化了控件和代码,因此只剩下一个属性)
Imports System.IO
Imports Globals
Imports Approver
Imports System.Data.SqlClient
Imports System.Data
Partial Class OrderEntry_Entry
Inherits System.Web.UI.Page
Protected Sub Page_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
Dim custPOLine As UserControl, lLoop As Long
for lLoop=1 to 5
custPOLine = Page.LoadControl("~/DistPOLine.ascx")
custPOLine.ID = "poLine" & Format(lLoop + 1, "000")
Me.plPOLines.Controls.Add(custPOLine)
'ctrlLabel = Me.FindControl("poLine" & Format(lLoop + 1, "000") & "_lbDistSKU") 'This is not working
'ctrlLabel.Text = dr("CustSKU").ToString
next
End Sub
End Class
答案 0 :(得分:1)
要访问用户控件的属性,您应该将用户控件声明为自定义用户控件的类型。
Dim custPOLine As DistPOLine
custPOLine.DistSKU = "YourString"
如果你确实想要找到控件并以这种方式编辑标签,你应该能够对你创建的用户控件进行查找控制,而不是你要添加它们的页面。
Dim lbl As Label = custPOLine.FindControl("lbDistSKU")
lbl.Text = "YourString"