您的位置:首页 > 编程语言 > ASP

转Asp.net 用户控件添加自定义事件

2012-04-09 15:01 525 查看
Asp.net 用户控件添加自定义事件

对于用户控件的使用有这样的特点。就是,当我们要求一个用户控件要实现特定的功能的时候,他可以在整个网站里面的页面上任意拖拽。但是,他的功能相对固定,也就是说在ascx文件中的代码是写死的,一旦要实现其他功能,就要将整个用户控件重做。这里介绍一种方法,要用户控件的可重复使用性更强。

前台代码:

就是一个简单的登录控件

<%@ Control Language=”C#” AutoEventWireup=”true” CodeFile=”LoginControl.ascx.cs” Inherits=”LoginControl” %>

<table border=”1”>

<tr>

<td colspan=”3” style=”background-color: #0099ff; text-align: center”>

<strong>用户登录</strong></td>

</tr>

<tr>

<td style=”width: 100px”>

用户名:</td>

<td colspan=”2”>

<asp:TextBox ID=”txtName” runat=”server” ValidationGroup=”group1”></asp:TextBox></td>

</tr>

<tr>

<td style=”width: 100px; height: 30px”>

密码:</td>

<td colspan=”2” style=”height: 30px”>

<asp:TextBox ID=”txtPassword” runat=”server” TextMode=”Password”></asp:TextBox></td>

</tr>

<tr>

<td colspan=”3” style=”text-align: center”>

<asp:RequiredFieldValidator ID=”RequiredFieldValidator1” runat=”server” ControlToValidate=”txtName”

ErrorMessage=”用户名为必填项” ValidationGroup=”group1”></asp:RequiredFieldValidator></td>

</tr>

<tr>

<td style=”width: 100px”>

<asp:Button ID=”Button3” runat=”server” Text=”Button” /></td>

<td style=”width: 100px; text-align: center”>

<asp:Button ID=”Button1” runat=”server” OnClick=”Button1_Click” Text=”登录” ValidationGroup=”group1”

Width=”56px” /></td>

<td style=”width: 100px; text-align: center”>

<asp:Button ID=”Button2” runat=”server” Text=”登出” Width=”54px” /></td>

</tr>

</table>

用户控件后台代码

public event EventHandler Authenticate;

protected void Page_Load(object sender, EventArgs e)

{

}

public void Button1_Click(object sender, EventArgs e)

{

if (Authenticate!=null)

{

Authenticate(this, new EventArgs());//如果用户自定义添加了事件,则该button会按指定的事件进行,而不会走默认事件。相反,会执行默认事件。

}

else

{

string connectString = ”Server=. ; DataBase=Test ; uid=sa ; pwd=cosecose ”;

string selectString = ”Select * from userInfo where Name=’” + txtName.Text.ToString() + ”’ and Password=’” + txtPassword.Text.ToString() + ”’”;

SqlConnection conn = new SqlConnection(connectString);

conn.Open();

SqlCommand cmd = new SqlCommand(selectString, conn);

SqlDataAdapter sda = new SqlDataAdapter();

sda.SelectCommand = cmd;

DataTable dt = new DataTable();

sda.Fill(dt);

if (dt.Rows.Count == 0)

{

Response.Write(”<script>window.alert(’密码或用户名输入错误!’)</script>”);

}

else

{

Response.Write(”<script>window.alert(’恭喜您,登录成功!’)</script>”);

}

conn.Close();

}

}

主页面代码

protected void Page_Load(object sender, EventArgs e)

{

Button btn =(Button)LoginControl1.FindControl(”Button2”);

btn.Click += new EventHandler(Show);

//提供第一种方法,通过findcontrol方法找到控件,然后对控件的事件进行添加。

LoginControl1.Authenticate += new EventHandler(Show);

//提供第二种方法,直接绑定上自己的定义事件。

}

protected void Show(object sender ,EventArgs e)

{

FormsAuthentication.SignOut();

Response.Write(”<script>window.alert(’用户已经成功退出!’)</script>”);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息