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

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

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


其中登陆的界面如下

[img]http://dl.iteye.com/upload/attachment/0066/5877/115a49ec-4b10-370d-b862-54e393ec4d60.jpg[/img]

为了便于理解下面的源代码,列举出各个控件的名字和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为存储过程,然后提示找不到找不到存储过程的错误!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值