使用TextBox的Usercontrol动作事件
本文关键字:事件 Usercontrol TextBox 使用 | 更新日期: 2023-09-27 18:09:54
我是asp.net的新手,我的问题是我有一个文本框和用户控制按钮默认。点击按钮后,我需要改变文本框的文本值(从用户控件的一些默认值)。
这可能吗?如果是,我需要在哪里写代码?
违约。aspx
<%@ Register Src="Text.ascx" TagName="Edit" TagPrefix="uc1" %>
<asp:TextBox ID="TextBox1" runat="server" Width="262px"></asp:TextBox>
<uc1:Edit Id="Edit2" runat="server" /></td>
Usercontrol - button
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Text.ascx.cs" Inherits="WebApplication4.WebUserControl1" %>
<asp:Button ID="Button1" runat="server" Text="Edit " OnClientClick="return confirm('Are you certain you want to Navigate?');" Width="341px" onclick="Button1_Click" />
如何从usercontrol中分组或触发(文本框值更改)?
从您的用户控件开始:
<asp:Button ID="Button1" runat="server" Text="Edit "
OnClientClick="return confirm('Are you certain you want to Navigate?');"
Width="341px" onclick="Button1_Click"/>
在后面的代码中,使用它来创建一个自定义事件,该事件在按钮'c click
上触发using System;
using System.Web.UI;
namespace TestApplication
{
public partial class Edit : UserControl
{
public string DefaultValue { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
private static object EditClickKey = new object();
public delegate void EditEventHandler(object sender, EditEventArgs e);
public event EditEventHandler EditClick
{
add
{
Events.AddHandler(EditClickKey, value);
}
remove
{
Events.RemoveHandler(EditClickKey, value);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
OnEditClick(new EditEventArgs(DefaultValue));
}
protected virtual void OnEditClick(EditEventArgs e)
{
var handler = (EditEventHandler)Events[EditClickKey];
if (handler != null)
handler(this, e);
}
public class EditEventArgs : EventArgs
{
private string data;
private EditEventArgs()
{
}
public EditEventArgs(string data)
{
this.data = data;
}
public string Data
{
get
{
return data;
}
}
}
}
}
"违约。页将包含您的新自定义事件的事件处理程序。
标记:
<asp:TextBox ID="TextBox1" runat="server" Width="262px"></asp:TextBox>
<uc1:Edit ID="Edit1" runat="server" OnEditClick="EditClick_OnEditClick" DefaultValue="default" />
背后的代码:
protected void EditClick_OnEditClick(object sender, TestApplication.Edit.EditEventArgs e)
{
TextBox1.Text = e.Data;
}
在Button1
的Button1_Click
事件中,您可以使用Page.FindControl()
方法获得对TextBox
的引用,如下所示:
protected void Button1_Click(...)
{
TextBox txtBox = (TextBox)this.Page.FindControl("TextBox1");
if(txtBox != null)
txtBox.Text = "Set some text value";
}