我们不可能将点击事件写到控件里,而是我们想吧事件处理得过程写在
调用控件的页面中,这是该怎么处理呢?
我的做法时使用delegate来实现这个功能!
具体做法如下:
下面是控件的html部分
1
<%
@ Control Language="C#" AutoEventWireup="true" CodeFile="ctlForm.ascx.cs" Inherits="ctlForm"
%>
2
<
table
>
3
<
tr
>
4
<
td
style
="width: 100px"
>
5
name
</
td
>
6
<
td
style
="width: 100px"
>
7
<
asp:TextBox
ID
="TextBox1"
runat
="server"
></
asp:TextBox
></
td
>
8
</
tr
>
9
<
tr
>
10
<
td
style
="width: 100px"
>
11
sex
</
td
>
12
<
td
style
="width: 100px"
>
13
<
asp:TextBox
ID
="TextBox2"
runat
="server"
></
asp:TextBox
></
td
>
14
</
tr
>
15
<
tr
>
16
<
td
style
="width: 100px"
>
17
</
td
>
18
<
td
style
="width: 100px"
>
19
<
asp:Button
ID
="Button1"
runat
="server"
OnClick
="Button1_Click"
Text
="测试"
/></
td
>
20
</
tr
>
21
</
table
>
22



2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

控件的cs部分
1
using
System;
2
using
System.Data;
3
using
System.Configuration;
4
using
System.Collections;
5
using
System.Web;
6
using
System.Web.Security;
7
using
System.Web.UI;
8
using
System.Web.UI.WebControls;
9
using
System.Web.UI.WebControls.WebParts;
10
using
System.Web.UI.HtmlControls;
11
12
public
partial
class
ctlForm : System.Web.UI.UserControl
13
{
14
protected void Page_Load(object sender, EventArgs e)
15
{
16
17
}
18
19
public delegate void ClickHander();
20
21
public ClickHander MyClickHandler = null;
22
23
public void Button1_Click(object sender, EventArgs e)
24
{
25
if (MyClickHandler != null)
26
{
27
MyClickHandler();
28
}
29
}
30
}
31

2

3

4

5

6

7

8

9

10

11

12

13



14

15



16

17

18

19

20

21

22

23

24



25

26



27

28

29

30

31

我们调用这个控件的页面写法如下:
1
<%
@ Page Language
=
"
C#
"
AutoEventWireup
=
"
true
"
CodeFile
=
"
testForm.aspx.cs
"
Inherits
=
"
testForm
"
%>
2
3
<%
@ Register Src
=
"
ctlForm.ascx
"
TagName
=
"
ctlForm
"
TagPrefix
=
"
uc1
"
%>
4
5
<!
DOCTYPE html PUBLIC
"
-//W3C//DTD XHTML 1.0 Transitional//EN
"
"
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
"
>
6
7
<
html xmlns
=
"
http://www.w3.org/1999/xhtml
"
>
8
<
head runat
=
"
server
"
>
9
<
title
>
无标题页
</
title
>
10
</
head
>
11
<
body
>
12
<
form id
=
"
form1
"
runat
=
"
server
"
>
13
<
div
>
14
<
uc1:ctlForm ID
=
"
CtlForm1
"
runat
=
"
server
"
/>
15
16
</
div
>
17
</
form
>
18
</
body
>
19
</
html
>
20
调用控件的cs代码如下

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

1
using
System;
2
using
System.Data;
3
using
System.Configuration;
4
using
System.Collections;
5
using
System.Web;
6
using
System.Web.Security;
7
using
System.Web.UI;
8
using
System.Web.UI.WebControls;
9
using
System.Web.UI.WebControls.WebParts;
10
using
System.Web.UI.HtmlControls;
11
12
public
partial
class
testForm : System.Web.UI.Page
13
{
14
protected void Page_Load(object sender, EventArgs e)
15
{
16
CtlForm1.MyClickHandler = new ctlForm.ClickHander(this.Test);
17
}
18
19
public void Test()
20
{
21
Response.Write("ok");
22
}
23
24
25
}

2

3

4

5

6

7

8

9

10

11

12

13



14

15



16

17

18

19

20



21

22

23

24

25
