asp.ne t登陆页面 源代码 及详细解释

下面将以一个小例子,来阐述登陆页面的跳转(含数据库的调用)

建立数据库Student   在数据库中建立表 users   其中包含字段 user ,password


其中登陆的界面如下



为了便于理解下面的源代码,列举出各个控件的名字和ID值:
lable1
lable2(用户名)TxtUser(用户名后面的文本框)
lable3(密码) TxtPassword(密码后面的文本框)
ButtonOK_Click(确定)       ButtonCancel_Click(取消)


基本思想:把输入的参数,作为查询条件,从数据库读出数据放入SqlDataReader中,然后从SqlDataReader 读出数据,若数据的条目不为0,则表示查询成功,则表示输入的用户和密码匹配,跳转到指定的页面
其中源代码,即aspx.cs文件如下
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using DataSet1TableAdapters;//添加引用


public partial class _Default : System.Web.UI.Page
{
     
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
    protected void ButtonOK_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection();//建立新的连接
        conn.ConnectionString = "Data Source =LIJIAXUAN-PC; Initial Catalog =Student;Integrated Security =SSPI "; //windows的验证方式
        conn.Open();//打开连接
      
        string sql = "select * from [users] where [user]='" + TxtUser.Text.Trim() + "' and [password]='" + TxtPassword.Text.Trim() + "'"; //Trim() 去掉前后字符串
        SqlCommand cmd = new SqlCommand(sql,conn);建立命令
        SqlDataReader da = cmd.ExecuteReader();
        int add = 0;
        while (da.Read()) { add++; }
        if (add == 0)
        {
            Response.Write("<script>javascript:alert('验证失败!请注册后再登录');history.go(-1);</script>");//提示错误

        }//history.go(-1)返回上页,并刷新上页
        else
        {
            Response.Redirect("default.aspx"); //跳转到指定页面
        }
           cmd.Dispose();
           conn.Close();//释放链接
      
    }
    protected void ButtonCancel_Click(object sender, EventArgs e)
    {
        TxtUser.Text = "";
        TxtPassword.Text= "";
        
    }
  
}
 
遇到的问题,总结
SqlCommand cmd = new SqlCommand(sql,conn);建立命令
“sql”,不应该加引号,不然会认为是sql为存储过程,然后提示找不到找不到存储过程的错误!

猜你喜欢

转载自lirujia00.iteye.com/blog/1486714