简体   繁体   English

从代码后台控制动态自定义控件属性

[英]Control dynamic Custom Control Properties from code-behind

I have a simple UserControl in ASP.NET (VB) with the following code pages: 我在ASP.NET(VB)中有一个简单的UserControl,其中包含以下代码页:

ASCX: ASCX:

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="DistPOLine.ascx.vb" Inherits="DistPOLine" %>

<asp:Label ID="lbDistSKU" runat="server" Text="Label"></asp:Label>

ASCX.VB 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

If I reference the control directly in an aspx page, I can set its DistSKU property without a problem. 如果直接在aspx页面中引用该控件,则可以毫无问题地设置其DistSKU属性。

<%@ Register src="DistPOLine.ascx" tagname="POline" tagprefix="POL" %>
<POL:POline ID="POline1" DistSKu="test Here" runat="server" /><br />

But in my code behind, where I create the user controls within a loop, I can't access the property directly, even by using FindControl and casting the control as a label. 但是,在后面的代码(在循环中创建用户控件的位置)中,即使使用FindControl并将控件转换为标签,也无法直接访问该属性。 The controls get created, but I need to manipulate them after creation. 控件已创建,但是创建后我需要对其进行操作。 (I've simplified the control and the code so only one property remains) (我简化了控件和代码,因此仅保留了一个属性)

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

To access the property of your user control, you should declare your user control as the type of your custom user control. 若要访问用户控件的属性,应将用户控件声明为自定义用户控件的类型。

Dim custPOLine As DistPOLine

custPOLine.DistSKU = "YourString"

And if you did want to find the control and edit the label that way, you should just be able to do a find control on the user control you created rather than the page you are adding them to. 而且,如果您确实想查找控件并以这种方式编辑标签,则应该只能够在您创建的用户控件上执行查找控件,而不是在添加控件的页面上进行查找。

Dim lbl As Label = custPOLine.FindControl("lbDistSKU")
lbl.Text = "YourString"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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