1. 程式人生 > >.net C#實現登入介面並進行跳轉

.net C#實現登入介面並進行跳轉

登入介面:

Userloagin.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Userloagin.aspx.cs" Inherits="UserLogin.Userloagin" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="text-align: center;margin-bottom: 40px;">

        登入畫面<br />
        <br />
        使用者ID:<asp:TextBox ID="id" runat="server" Height="20px" Width="180px"></asp:TextBox>
        <br />
        <br />
         密   碼:<asp:TextBox ID="password" runat="server" Height="20px" Width="180px"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button" runat="server" Height="24px" OnClick="Button_Click" Text="登入" Width="75px" />
        <br />
        <br />
        <asp:Label ID="Label" runat="server" ForeColor="Red"></asp:Label>
        <br />
    
    </div>
    </form>
</body>
</html>
Userloagin.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//新增以下參照
using System.Windows.Forms;
//using Oracle.DataAccess.Client;//oracle自帶的
using System.Data.OracleClient;
using System.Data.SqlClient;//using Oracle.DataAccess.Client;
using System.Data;//注意


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


        protected void Button_Click(object sender, EventArgs e)
        {
            if (id.Text == "")
            {
                //MessageBox.Show("使用者ID必須存在入內!");//using System.Windows.Forms;
                Response.Write(@"<script>alert('使用者名稱不能為空!');</script>");
            }
            if (password.Text == "")
            {
                //MessageBox.Show("密碼不能為空!");
                Response.Write(@"<script>alert('使用者密碼不能為空!');</script>");
            }
            //連線Oracle
            string connString = "User ID=system;Password=Lg_12358134711;Data Source=(DESCRIPTION = (ADDRESS_LIST= (ADDRESS = (PROTOCOL = TCP)(HOST = 10.167.23.31)(PORT = 1521))) (CONNECT_DATA = (SID = oracletest)))";
            OracleConnection conn = new OracleConnection(connString);
            conn.Open();



            //方法一 
            //DataSet 是用來儲存資料庫資料的。資料庫 DataSet,表 DataTable,列 DataColumn,行 DataRow
            //DataSet 和 物理資料庫是兩個客體,要使這兩個客體保持一致,就需要使用 DataAdapter 類來同步兩個客體。
            //一般來說操作流程是:使用 DataAdapter 把物理資料庫中的資料填充到 DataSet 中的 DataTable 裡。當我們對記憶體中的 DataSet 做了增、刪、改操作後,可以使用 DataAdapter 同步回資料庫。
            //http://blog.163.com/jianzhong_w/blog/static/3833113620077245104435/


            //建立DataSet  SqlDataAdapter物件
            //string strSql = "select * from USER_MST";
            //OracleDataAdapter odr = new OracleDataAdapter(strSql,conn);
            //try
            //{
            //    DataSet ds = new DataSet();
            //    odr.Fill(ds, "USER_MST");
            //    for (int i = 0; i < ds.Tables["USER_MST"].Rows.Count; i++)
            //    {
            //        string User = id.Text;
            //        string Psw = id.Text.Trim();
            //        string db_Uid = ds.Tables["USER_MST"].Rows[i]["USERID"].ToString();
            //        string db_Psw = ds.Tables["USER_MST"].Rows[i]["PASSWORD"].ToString();
            //        string username = ds.Tables["USER_MST"].Rows[i]["USERNAME"].ToString();
            //        if (id.Text == db_Uid && password.Text == db_Psw)
            //        {
            //            Label.Text = "登陸成功";
            //            Session["username"] = username;
            //            Session["userid"] = db_Uid;
            //            Server.Transfer("menu.aspx");
            //        }
            //    }
            //    Label.Text = "登陸失敗!使用者ID或密碼錯誤!";
            //}
            //catch (OracleException ex)
            //{
            //    Console.WriteLine(ex.Message);
            //}
            //finally
            //{
            //    conn.Close();
            //}


            //string strOrcSelect = "select USERNAME from USER_MST where USERID=@USERID and PASSWORD=@PASSWORD";
            //OracleCommand comm = new OracleCommand(strOrcSelect, conn);
            //comm.Parameters.Add("USERID", id.Text);
            //comm.Parameters.Add("PASSWORD", password.Text);
            //OracleDataReader sdr = comm.ExecuteReader();
            //while (sdr.Read())
            //{
            //    Label.Text = "登陸成功";
            //    Session["USERID"] = id.Text;
            //    Session["PASSWORD"] = password.Text;
            //    Response.Redirect("menu");
            //}
            // Label.Text = "登陸失敗!使用者ID或密碼錯誤!";




            try
            {
                string userid = id.Text;
                string psd = password.Text;


                //Oracle
                //string strOrcSelect = "select * from USER_MST where USERID=" + userid + " and PASSWORD=" + psd;//select * from USER_MST where USERID= 12 and PASSWORD = 123
                //string strOrcSelect = "select * from USER_MST where USERID='userid' and PASSWORD='psd'";//select * from USER_MST where USERID='userid' and PASSWORD='psd';
                //上述表示錯誤,應為下面的兩種形式
                //形式一:
                //string strOrcSelect = "select * from [USER_MST] where id='" + userid + "' and password='" + psd + "'";
                //形式二:
                //string strOrcSelect = string.Format("select count(*) from USER_MST where USERID= '{0}'and PASSWORD = '{1}'", this.id.Text.Trim(), this.password.Text.Trim());


                //string strOrcSelect = string.Format("select count(*) from USER_MST where USERID= '{0}'and PASSWORD = '{1}'", this.id.Text.Trim(), this.password.Text.Trim());
                //OracleCommand comm = new OracleCommand(strOrcSelect, conn);
                //if (comm.ExecuteScalar() == null)//可能會失敗,需要進行判斷
                //{
                //    Label.Text = "登陸失敗!使用者ID或密碼錯誤!";
                //}
                //else
                //{                
                //    int i = int.Parse(comm.ExecuteOracleScalar().ToString());
                //}




                //ExecuteScalar():從資料庫中檢索單個值。執行查詢,並返回查詢所返回的結果集中第一行的第一列或空引用(如果結果集為空).忽略其他列或行.
                //ExecuteScalar()所求的資料集為空或不存在兩種情況:
                //object obj = comm.ExecuteScalar(); 
                //情況一:if (obj == System.DBNull.Value) { MessageBox.Show("Result Is Null 資料集的行數為一");}
                //情況二:if (obj == null )  {MessageBox.Show("資料集的行數為零");}


                //OracleCommand cmd = conn.CreateCommand(); //建立命令物件
                //cmd.CommandText = "select USERNAME from USER_MST where id='" + userid + "'";  //提供oracle命令
                //不可以使用:string strOrcSelect = string.Format("select count(*)  from USER_MST where USERID = '{0}'and PASSWORD = '{1}'", this.id.Text.Trim(), this.password.Text.Trim());
                //ExecuteReader()和ExecuteScalar()的用法


                string strOrcSelect = "select USERNAME from USER_MST where USERID='" + userid + "'and PASSWORD='" + psd + "'";//注意使用'" + userid + "','" + psd + "'中單引號可以加也可以不加
                //string strOrcSelect = string.Format("select USERNAME from USER_MST where USERID = '{0}' and PASSWORD = '{1}'", this.id.Text.Trim(), this.password.Text.Trim());


                OracleCommand cmd = new OracleCommand(strOrcSelect, conn);


                if (cmd.ExecuteScalar() == null || cmd.ExecuteScalar()== System.DBNull.Value)//comm.ExecuteScalar()需要進行判斷,資料庫查詢結果為空時;注意大寫NULL是錯誤的
                {
                    //MessageBox.Show("登陸失敗!使用者ID或密碼錯誤!");
                    //Response.Write(@"<script>alert('登陸失敗!使用者ID或密碼錯誤!')</script>");
                    //Response.Write(@"<script language='javascritp'>alert('登陸失敗!使用者ID或密碼錯誤!');location.href='Userloagin.aspx'</script>");
                    //Page.ClientScript.RegisterStartupScript(GetType(), "error", "<script>alert('使用者ID或密碼錯誤!');</script>");
                    Label.Text = "登陸失敗!使用者ID或密碼錯誤!";
                }
                else
                {
                    int i = int.Parse(cmd.ExecuteScalar().ToString());//comm.ExecuteScalar()大於0
                    Label.Text = "登入成功";
                    //利用Session進行儲存userid,username


                    //方法二:
                    //OracleDataReader讀取多個結果集,OracleDataReader中的NextResult()來接收多個結果集
                    //DataReader物件提供只讀單向資料的快速傳遞。
                    //單向:您只能依次讀取下一條資料;只讀:DataReader中的資料是隻讀的,不能修改;相對地,DataSet中的資料可以任意讀取和修改
                    //只可使用:select USERNAME  from USER_MST where USERID = userid and PASSWORD = psd;


                    //OracleDataReader red = cmd.ExecuteReader(); //執行命令返回結果指派給DataReader物件
                    //while (red.Read())//迴圈列
                    //{
                    //    string username = red["USERNAME"].ToString();
                    //    Session["username"] = username;
                    //    Session["userid"] = userid;
                    //    Server.Transfer("menu.aspx");
                    //}




                    //方法三
                    //只可使用:select USERNAME  from USER_MST where USERID = userid and PASSWORD = psd;


                    string username = cmd.ExecuteScalar().ToString();
                    Session["username"] = username;
                    Console.Write(Session["username"].ToString());
                    Session["userid"] = userid;
                    Response.Redirect("menu.aspx"); //Server.Transfer("menu.aspx");
                }
            }
            catch (OracleException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                conn.Close();
            }
        }
    }
}


登陸成功後跳轉到系統主介面:

menu.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="menu.aspx.cs" Inherits="UserLogin.main" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="text-align: center">
    
        歡迎進入該系統</div>
        <p>
            使用者ID:<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </p>
        <p>
            使用者名稱:<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
        </p>
    </form>
    <p>
         </p>
</body>
</html>
menu.aspx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace UserLogin
{
    public partial class main : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Label1.Text = Session["userid"].ToString();
            Label2.Text = Session["username"].ToString();
        }
    }
}