[英]Usercontrol action event with TextBox
我是asp.net的新手,我的問題是我在default.aspx中有一個TextBox和用戶控件Button,單擊Button之后,我需要更改TextBox的文本值(用戶控件中的某些默認值)。
如果可以的話,我需要在哪里編寫代碼?
Default.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>
用戶控件-按鈕
<%@ 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"/>
在后面的代碼中,使用此代碼創建一個自定義事件,該事件將在button'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;
}
}
}
}
}
“ Default.aspx”頁面將包含新的自定義事件的事件處理程序。
標記:
<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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.