0
我有一個組合自定義控件發送電子郵件。郵件按鈕點擊發送。但是,我點擊按鈕兩次後發送郵件。有人知道爲什麼會發生這種情況,我該如何解決?下面是代碼:自定義控件OnButtonClick事件處理程序覆蓋C#
namespace EmailControl
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1>")]
public class ServerControl1 : WebControl,INamingContainer
{
public string Text
{
get { return ViewState["Text"] as string ?? "[" + this.ID + "]"; }
set { ViewState["Text"] = value; }
}
public string Host
{
get { return ViewState["host"] as string ?? "[" + this.ID + "]"; }
set { ViewState["host"] = value; }
}
public string From
{
get { return ViewState["from"] as string ?? "[" + this.ID + "]"; }
set { ViewState["from"] = value; }
}
public int Port
{
get { return (int) ViewState["port"]; }
set { ViewState["port"] = value; }
}
public string UserName
{
get { return ViewState["user"] as string ?? "[" + this.ID + "]"; }
set { ViewState["user"] = value; }
}
public string Password
{
get { return ViewState["pass"] as string ?? "[" + this.ID + "]"; }
set { ViewState["pass"] = value; }
}
TextBox txtEmail;
TextBox txtBody;
TextBox txtSubject;
Button btnSend;
protected override void CreateChildControls()
{
txtEmail = new TextBox();
txtEmail.ID = "txtEmail";
txtEmail.AutoPostBack = true;
LiteralControl l1 = new LiteralControl("<br/>");
txtSubject = new TextBox();
txtSubject.ID = "txtSubject";
txtEmail.AutoPostBack = true;
this.Controls.Add(txtEmail);
this.Controls.Add(txtSubject);
LiteralControl l2= new LiteralControl("<br/>");
txtBody = new TextBox();
txtBody.ID = "txtBody";
txtBody.AutoPostBack = true;
txtBody.TextMode = TextBoxMode.MultiLine;
txtBody.Width = 200;
txtBody.Height = 200;
this.Controls.Add(txtBody);
btnSend = new Button();
btnSend.ID = "btnSend";
btnSend.Width = 100;
btnSend.Text = "Send";
btnSend.Click += new EventHandler(OnButtonClick);
this.Controls.Add(btnSend);
}
protected void OnButtonClick(object sender,EventArgs e)
{
TextBox txtEmail = (TextBox)this.FindControl("txtEmail");
MailMessage msg = new MailMessage(From,txtEmail.Text);
TextBox txtSubject = (TextBox)this.FindControl("txtSubject");
TextBox txtBody = (TextBox)this.FindControl("txtBody");
msg.Subject = txtSubject.Text;
msg.Body = txtBody.Text;
SmtpClient smtp = new SmtpClient();
smtp.Host = Host;
smtp.Port = Convert.ToInt32(Port);
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential(UserName,
Password);
smtp.Send(msg);
}
}
}
在ASPX頁面的代碼:
protected void Page_Load(object sender, EventArgs e)
{
ServerControl11.Host = "smtp.gmail.com";
ServerControl11.Port =25;
ServerControl11.UserName = "*******************@gmail.com";
ServerControl11.Password = "************";
ServerControl11.From = "******************@gmail.com";
}
爲了吸引更多的答案,你應該添加相應的語言或工具,你正在使用的標籤。你可以通過[編輯你的問題](http://stackoverflow.com/posts/11814971/edit)並在編輯頁面底部添加標籤來實現。 – assylias 2012-08-05 08:37:54
您是否嘗試調試它?你的事件是否被解僱了兩次? – 2012-08-05 11:34:13