用户控件
1,添加新项,选择web用户控件,命名为Login.ascx,然后在设计视图中添加几个控件,然后添加table,再添加后台代码,最后添加到其他aspx页面。
(1)下面是html源码:
html
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="Login.ascx.cs" Inherits="WebApplication2.userControl.Login" %> <table> <tr> <td><asp:Label ID="Label1" runat="server" Text="用户名"></asp:Label></td> <td><asp:TextBox ID="TxtUserName" runat="server" ></asp:TextBox></td> </tr> <tr> <td><asp:Label ID="Label2" runat="server" Text="密码"></asp:Label></td> <td><asp:TextBox ID="TxtPassword" runat="server"></asp:TextBox></td> </tr> <tr> <td colspan="2"><asp:CheckBox ID="CheckBox1" Text="是否保持长时间登录状态" runat="server" /></td> </tr> <tr> <td colspan="2"><asp:Button ID="BtnLogin" runat="server" Text="登录" OnClick="BtnLogin_Click" /></td> </tr> </table>
(2)下面是后台代码:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Configuration; namespace WebApplication2.userControl { public partial class Login : System.Web.UI.UserControl { SqlConnection conn; SqlCommand comm; SqlDataReader dreader; protected void Page_Load(object sender, EventArgs e) { } protected void BtnLogin_Click(object sender, EventArgs e) { string username=TxtUserName.Text.Trim(); string password=TxtPassword.Text.Trim(); string connStr ="server=.;database=db_OA;uid=sa;pwd=123456" ;//System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"].ToString(); conn = new SqlConnection(connStr); conn.Open(); string sql="select * from sysUser where userName=@userName and userPwd=@password"; comm = new SqlCommand(sql, conn); comm.Parameters.Add(new SqlParameter("@username",username)); comm.Parameters.Add(new SqlParameter("@password",password)); dreader = comm.ExecuteReader(); if (dreader.Read()) { HttpCookie cookie = new HttpCookie("username", username); if (CheckBox1.Checked) { cookie.Expires = DateTime.Now.AddDays(7); } Response.Cookies.Add(cookie); Response.AppendHeader("refresh", "3,url=WebForm1.aspx"); } else { Response.Write("<script>alert('用户名或密码错误')</script>"); } dreader.Close(); conn.Close(); } } }
(3)然后把这个用户控件拖拽到其他页面就行了。
这里面很多地方可以通过封装,将属性暴露给外面,如TxtUserName,连接字符串等等。
参考:http://blog.csdn.net/z470208239/article/details/6144713