TestUC.ascx设计代码
<asp:TextBox ID="txtbox1" runat="server" ClientIDMode="Static" placeholder="Enter Some Text" ></asp:TextBox><br />
<asp:Button ID="btn1" runat="server" Text="Click" OnClick="btn1_Click" ClientIDMode="Static" />
Test.aspx页面代码
<%@ Register Src="~/WebUserControls/TestUC.ascx" TagName="WebUserControlTest"
TagPrefix="uctest" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphBody" runat="server">
<asp:Label ID="lbl1" runat="server" >Label</asp:Label>
<uctest:WebUserControlTest ID="ucTest" runat="server"></uctest:WebUserControlTest>
</asp:Content>
输出:
我需要 ..
步骤1:在文本框中输入一些文本
步骤2:然后我单击单击按钮[注意:这两个控件是从UserControl绑定的。]
步骤3:在文本框中输入的文本显示在标签中[注释标签存在于Aspx页面中]
您将需要有一个自定义事件,并且还需要像这样在UserControl中公开的Text
属性TextBox
。
public partial class YourUserControl : UserControl
{
public String Text
{
get
{
return this.txtBox1.Text;
}
//write the setter property if you would like to set the text
//of the TextBox from your aspx page
//set
//{
// this.txtBox1.Text = value;
//}
}
public delegate void TextAppliedEventHandler(Object sender, EventArgs e);
public event TextAppliedEventHandler TextApplied;
protected virtual void OnTextApplied(EventArgs e)
{
//Taking a local copy of the event,
//as events can be subscribed/unsubscribed asynchronously.
//If that happens after the below null check then
//NullReferenceException will be thrown
TextAppliedEventHandler handler = TextApplied;
//Checking if the event has been subscribed or not...
if (handler != null)
handler(this, e);
}
protected void yourUserControlButton_Click(Object sender, EventArgs e)
{
OnTextApplied(EventArgs.Empty);
}
}
然后,在您放置的aspx页面中YourUserControl
(或您正在从后面的代码中动态添加它),您可以像这样订阅此事件。
protected void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
yourUserControl.TextApplied += new YourUserControl.TextAppliedEventHandler(yourUserControl_TextApplied)
}
}
您可以像这样在页面中使用用户控件的自定义事件。
protected void yourUserControl_TextApplied(Object sender, EventArgs e)
{
yourLabelInYourPage.Text = yourUserControl.Text;
}
你完成了...
编辑:您可以根据需要重命名控件和事件。我仅将名称用于示例目的。
编辑:在网站项目中,如果要动态添加用户控件,则可能需要ASP
像这样在页面中包含名称空间。
using ASP;
并将其添加Directive
到页面的aspx标记中。
<%@ Reference Control="~/PathToYourUserControl/YourUserControl.ascx" %>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句