现在的位置: 首页 > 综合 > 正文

用户控件的事件

2014年03月15日 ⁄ 综合 ⁄ 共 2122字 ⁄ 字号 评论关闭

1.baseUserControl.ascx:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="baseUserControl.ascx.cs" Inherits="baseUserControl" %>
<asp:Button ID="btn1" runat="server" Text="hi" OnClick="btn1_Click" />
baseUserControl.ascx.ca:

public partial class baseUserControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    public event EventHandler myClick;
    protected void btn1_Click(object sender, EventArgs e)
    {
        Session["btn_id"] = btn1.ID;
        if (myClick != null)
        {
            EventArgs args = new EventArgs();
            myClick(this, args);
        }
    }
}

2.TestUserControl.ascx:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="TestUserControl.ascx.cs" Inherits="TestUserControl" %>
<%@ Register Src="baseUserControl.ascx" TagName="baseUserControl" TagPrefix="uc1" %>
<asp:Table ID="test" BorderWidth="1" GridLines="Both" runat="server" >
    <asp:TableRow>

    </asp:TableRow>
</asp:Table>
<asp:Label ID="l1" runat="server" ></asp:Label>

TestUserControl.ascx.cs:
public partial class TestUserControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        doFunction();
    }
    private void doFunction()
    {
        test.Rows[0].Cells.Clear();
        TableCell tc1 = new TableCell();
        baseUserControl c_1 = (baseUserControl)LoadControl("baseUserControl.ascx");
        c_1.ID = "1";
        c_1.myClick += new EventHandler(c_b_Click);
        tc1.Controls.Add(c_1);
        test.Rows[0].Cells.Add(tc1);
    }

    protected void c_b_Click(object sender, EventArgs e)//就是这个event,点两次才执行一次.why?
    {
        doFunction();//重新生成这个table,是必须的.
        l1.Text = l1.Text + "a";
    }
}

3.test.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>

<%@ Register Src="TestUserControl.ascx" TagName="TestUserControl" TagPrefix="uc1" %>

<!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">
<link rel="stylesheet" type="text/css" href="mla.css" />
    <title>Untitled Page</title>
</head>
<body>
<form id="loungeForm" runat="server">
    <uc1:TestUserControl ID="TestUserControl1" runat="server" />
</form>
</body>
</html>

抱歉!评论已关闭.