如何在同一页面上的另一个 Ascx 控件中访问一个 Ascx 控件中的值

How to access value in one Ascx control in another Ascx control on the same page

我有一个 aspx 页面,它有两个用户控件,一个带有网格视图,另一个带有标签,用于在用户登录时显示用户数据。现在我想使用一列中的数据在网格视图中显示在第二个用户控件的标签中。我怎样才能做到这一点。 gridview 中的数据会根据每个用户的安全性 role.any 输入而变化。谢谢

Gridview 用户控件在具有您需要的信息时引发自定义事件。该事件在主页中处理,并通过 public 属性 分配给带有标签的 UserControl,该标签可以访问控件中嵌入的标签文本。

Default.aspx

包含两个用户控件的页面

<%@ Page Title="Home Page" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.vb" Inherits="WhosebugJunkVB._Default" %>
<%@ Register Src="~/WebUserControlGridView1.ascx" TagPrefix="uc1" TagName="WebUserControlGridView1" %>
<%@ Register Src="~/WebUserControlLabel1.ascx" TagPrefix="uc1" TagName="WebUserControlLabel1" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <uc1:WebUserControlGridView1 runat="server" id="WebUserControlGridView1" />
    <uc1:WebUserControlLabel1 runat="server" id="WebUserControlLabel1" />
</asp:Content>

Default.aspx.vb

通过从 GridView 用户控件引发的事件将文本分配给 Label 用户控件的代码

Public Class _Default
    Inherits Page

    Private Sub WebUserControlGridView1_ReallyImportantLabelTextHandler(sender As Object, e As GridViewLabelEvent) _
      Handles WebUserControlGridView1.ReallyImportantLabelTextHandler

        WebUserControlLabel1.ReallyImportLabelText = e.ImportantLabelText

    End Sub
End Class

GridView 用户控件的代码隐藏

' Define a custom EventArgs class to pass some really important text
Public Class GridViewLabelEvent
    Inherits EventArgs

    Public Property ImportantLabelText As String
End Class

' The user control with a GridView
Public Class WebUserControlGridView1
    Inherits System.Web.UI.UserControl

  Public Event ReallyImportantLabelTextHandler As EventHandler(Of GridViewLabelEvent)

  Private Sub GridView1_DataBound(sender As Object, e As EventArgs) Handles GridView1.DataBound
    Dim gvle As New GridViewLabelEvent
    gvle.ImportantLabelText = "This is really important"
    RaiseEvent ReallyImportantLabelTextHandler(Me, gvle)
  End Sub
End Class

标签用户控件的代码隐藏

Public Class WebUserControlLabel1
    Inherits System.Web.UI.UserControl

    ' Property to assign Label Text
    Public Property ReallyImportLabelText As String
        Get
            Return Label1.Text
        End Get
        Set(value As String)
            Label1.Text = value
        End Set
    End Property
End Class