Usercontrol action event with TextBox
I am new to asp.net, My problem is I have one TextBox and user control Button in default.aspx ,After clicking the Button I need change the text value of TextBox(some default val开发者_如何学运维ue from user control).
Is that possible?If Yes,where i need to write the code?
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>
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" />
how to group or ,fire that(text box value change) from usercontrol ?
Starting from your user control:
<asp:Button ID="Button1" runat="server" Text="Edit "
OnClientClick="return confirm('Are you certain you want to Navigate?');"
Width="341px" onclick="Button1_Click"/>
In the code behind use this to create a custom event which fires on the 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;
}
}
}
}
}
The "Default.aspx" page will contain the Event Handler for your new Custom Event.
markup:
<asp:TextBox ID="TextBox1" runat="server" Width="262px"></asp:TextBox>
<uc1:Edit ID="Edit1" runat="server" OnEditClick="EditClick_OnEditClick" DefaultValue="default" />
Code Behind:
protected void EditClick_OnEditClick(object sender, TestApplication.Edit.EditEventArgs e)
{
TextBox1.Text = e.Data;
}
In the Button1_Click
event of Button1
you can get the reference to TextBox
using Page.FindControl()
method, like this:
protected void Button1_Click(...)
{
TextBox txtBox = (TextBox)this.Page.FindControl("TextBox1");
if(txtBox != null)
txtBox.Text = "Set some text value";
}
精彩评论