2011-09-26 46 views
1

用戶控件動作事件我是新來asp.net, 我的問題是我在Default.aspx的一個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" /> 

如何從用戶控件組或大火,(文本框值的變化)?

回答

2

從用戶控件開始:

<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點擊

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; 
     } 
1

Button1Button1_Click事件中,你可以得到使用Page.FindControl()方法參考TextBox,像這樣:

protected void Button1_Click(...) 
{ 
    TextBox txtBox = (TextBox)this.Page.FindControl("TextBox1"); 
    if(txtBox != null) 
     txtBox.Text = "Set some text value"; 
}