asp.net 3.5实现access登录(不用login控件)

发布时间:2020-04-13编辑:脚本学堂
本文介绍下,在asp.net 3.5环境中,实现access访问登录的例子,这里没有使用login控件,有需要的朋友参考下吧。

分享一例代码:
实现asp.net 3.5中的access登录,非login控件实现。

1,login.aspx页面文件:(母版页为MasterPage.master)
 

复制代码 代码示例:
<%@ Page Title="" Language="C#" MasterPageFile="MasterPage.master" AutoEventWireup="true" CodeFile="AdminLogin.aspx.cs" Inherits="manager_AdminLogin" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MasterMain" Runat="Server">
    <div id="page">
    <div id="page-bgtop">
      <div id="connect">
       <asp:Label ID="Label1" runat="server" Text="姓名"></asp:Label>
        <asp:TextBox ID="TextBoxName" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Label ID="Label2" runat="server" Text="密码"></asp:Label>
        <asp:TextBox ID="TextBoxPwd" runat="server" TextMode="Password"></asp:TextBox>
        <br />
        <br />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="ButtonLogin" runat="server" onclick="ButtonLogin_Click"
            Text="登录" />
        &nbsp;&nbsp;&nbsp;
        <asp:Label ID="message" runat="server"></asp:Label>
      </div>
    </div>
  </div>
</asp:Content>

2,
login.aspx.cs代码文件:
 

复制代码 代码示例:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.OleDb;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class manager_AdminLogin : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void ButtonLogin_Click(object sender, EventArgs e)
    {
        try
        {
            OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + Server.MapPath("App_Data/sitedb.mdb"));//建立access数据库文件sitedb.mdb(相对路径)的数据库连接
            con.Open(); //打开数据库
            string sql; //定义字符串sql
            sql = "select count(*) from usertab where username='" + this.TextBoxName.Text + "' and userpwd='" + this.TextBoxPwd.Text + "'";//建立sql查询语句
            OleDbCommand cmd = new OleDbCommand(sql, con);//建立数据集
            int state =Convert.ToInt32( cmd.ExecuteScalar());//执行sql语句,并返回获得值
            if (state == 0 || state > 1)//如果数据中没有记录或有多条记录则抱错
            {
                message.Text = "用户不存在,请检测用户名和密码是否正确!";
            }
            else//正确数据指向登陆后页面
            {
                Session["admin"] = TextBoxName.Text;
                Response.Redirect("manager/AdminPage.aspx");//指向登陆后页面
            }
        }
        catch
        {
            message.Text = "无法进行数据连接";
        }
    }
}