如果在c#中连接并存储session的值 [英] if in connection in c# and store the value of session

查看:73
本文介绍了如果在c#中连接并存储session的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从C#开始,我试图制作一个简单的登录代码,该代码将用户名和密码的值与访问数据库进行比较,并且Gridview显示数据,但是当我但是在Gridview.Rows上是否返回else语句

I begin in c# I''m trying to make a simple login code which compare the value of username and password with access database and Gridview show data but when i but if and else on Gridview.Rows return else statement

Session["u1"] = txt_username.Text;
        
        OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=J:\\hg\\h12\\bbc2\\App_Data\\center_database.mdb");
        try
        {
            con.Open();
            OleDbCommand cmd = con.CreateCommand();
            cmd.CommandText = "select * from P_Data where S_Fname='" +    
            Session["u1"].ToString() + "'and S_Code='" + txt_password.Text + "'";
            OleDbDataReader r = cmd.ExecuteReader();
             GridView1.DataSource = r;
            
            if (GridView1.Rows.Count > 0)
            {
                GridView1.DataBind();
            }
            else
            {
                Label2.Text = ("invalid username or password <br> please sign up");
            }

            con.Close();
        }
        catch (Exception)
        {
            Response.Redirect("Reg.aspx");
        }

推荐答案

我如下修改了您的代码.

I modified your code as follows.

OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=J:\\hg\\h12\\bbc2\\App_Data\\center_database.mdb");
           try
           {
               con.Open();
               OleDbCommand cmd = con.CreateCommand();
               cmd.CommandText = "select * from P_Data where S_Fname='" +
               Session["u1"].ToString() + "' and S_Code='" + txt_password.Text + "'";
               OleDbDataReader r = cmd.ExecuteReader();

               if (r.HasRows)// Check if reader has rows
               {
                   GridView1.DataSource = new DataTable().Load(r).DefaultView;
                   GridView1.DataBind();
               }
               else
               {
                   Label2.Text = ("invalid username or password <br> please sign up");
               }

               con.Close();
           }
           catch (Exception)
           {
               Response.Redirect("Reg.aspx");
           }


基本上也可能是您的用户输入了错误的密码(或者您要比较的列是错误的).
结果,您不会获得选择查询返回的任何值,而是进入if循环.

也许也值得考虑重新构建查询.
Basically it could also be that your user is entering an incorrect password (or the column you are comparing with are wrong).
As a result, you dont get any values returned by the select query and you go into the if loop.

It might be worthwhile to consider reframing your query too.


这篇关于如果在c#中连接并存储session的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆