aspx页面源代码(Default.aspx and Default.aspx.cs
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UserControl._Default" %>
<%@ Register Src="~/WebUserControl1.ascx" TagPrefix="cc1" TagName="user" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>无标题页</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<cc1:user runat="server"></cc1:user>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>
</form>
</body>
</html>
后台(Default.aspx.cs):
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('22222');", true);
}
}
用户控件(WebUserControl1.ascx)源代码:
<table cellspacing="0" rules="all" bordercolor="#CCCCCC" border="1" id="tbList" style="border-color: #CCCCCC;
width: 100%; border-collapse: collapse;" runat="server">
<tr class="DGHeaderStyle" id="trHeader">
</tr>
<tr id="trInput">
<td>
<asp:TextBox ID="TextBox1" runat="server" Width="150px" class="TextBoxStyle"
AutoPostBack="true" OnTextChanged="txtInput_TextChanged" Style="color: #666"></asp:TextBox>
</td>
</tr>
<tr id="trTotal">
</tr>
</table>
用户控件后台(WebUserControl1.ascx.cs):
public partial class WebUserControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell cell = new HtmlTableCell();
cell.InnerText = "111";
row.Cells.Add(cell);
tbList.Rows.Insert(1, row);
}
protected void txtInput_TextChanged(object sender, EventArgs e)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('11111');", true);
}
}
问题所在:触发了文本框的change事件后,在点击按钮结果文本框的changge事件与按钮的点击事件
同时触发(照理它应该只触发按钮事件)。
是因为你在点击按钮的时候,焦点离开了文本框,由此出发了文本框的Change事件,一个办法就是,把文本框的Change事件尽量写到前台,这样在点按钮的时候,会先执行前台的代码。
动态生成的Table行代码放到if(!IsPostBack)里。
你网页的默认焦点应该是按钮 而不是textbox