如何在登录表单中添加限制?

时间:2014-05-19 03:13:25

标签: c# sql sql-server

我正在为我的系统创建登录表单,并希望添加用户和管理员帐户。我在我的数据库中所做的是为我的用户创建一个具有特定用户类型的表U_Type将是1 = admin或2 = user。

我想添加一个if语句来调用我的列名U_Type并将其比作1或2.下面是我未完成的代码。我正在使用visual studio 2008 c#和ms sql 2005

这是我的代码:

float Outcome;
    private void button1_Click(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection();

    conn.ConnectionString = "Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True";
    conn.Open();

    String txtUser = textBox1.Text;
    String txtPass = textBox2.Text;

    string query = "SELECT * FROM tblUsers WHERE U_Name=@U_Name AND U_Pass=@U_Pass AND U_Type=@type";
    SqlCommand cmd = new SqlCommand(query, conn);
    cmd.Parameters.Add(new SqlParameter("@U_Name", txtUser));
    cmd.Parameters.Add(new SqlParameter("@U_Pass", txtPass));
    cmd.Parameters.Add(new SqlParameter("@type", type));

    SqlDataReader dr = cmd.ExecuteReader();

    if (textBox1.Text.Trim().Length == 0)
    {
        MessageBox.Show("Login Failed");
        Outcome = Convert.ToInt32(lblOutcome.Text);
        Outcome = Outcome - 1;
        textBox1.Clear();
        textBox2.Clear();

        lblOutcome.Text = Outcome.ToString();
        if (Outcome == 0)
        {
            MessageBox.Show("You have reached the maximum number of trial");
            this.Close();
        }
    }

    else if (textBox2.Text.Trim().Length == 0)
    {
        MessageBox.Show("Login Failed");
        Outcome = Convert.ToInt32(lblOutcome.Text);
        Outcome = Outcome - 1;
        textBox1.Clear();
        textBox2.Clear();

        lblOutcome.Text = Outcome.ToString();
        if (Outcome == 0)
        {
            MessageBox.Show("You have reached the maximum number of trial");
            this.Close();
        }
    }

    else if (dr.HasRows == true)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True";
        SqlCommand command = new SqlCommand("SELECT U_Name ='"+textBox1.Text+"', U_Pass = '" +textBox2.Text+"', U_Type = 1 FROM tblUsers",con);


        con.Open();
        SqlDataReader sdr = command.ExecuteReader();


        if ()
        {
            MessageBox.Show("Login Successful");
            MDIParent1 settingsForm = new MDIParent1();
            settingsForm.Show();
            this.Hide();
        }
        else
        {
            MessageBox.Show("Login Successful");
            MDIParent2 settingsForm = new MDIParent2();
            settingsForm.Show();
            this.Hide();
        }
    }


        else
        {
            MessageBox.Show("Login Failed");
            Outcome = Convert.ToInt32(lblOutcome.Text);
            Outcome = Outcome - 1;
            textBox1.Clear();
            textBox2.Clear();

            lblOutcome.Text = Outcome.ToString();
            if (Outcome == 0)
            {
                MessageBox.Show("You have reached the maximum number of trial");
                this.Close();
            }
        }
    }

我希望if语句在这里

  else if (dr.HasRows == true)
        {
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True";
            SqlCommand command = new SqlCommand("SELECT U_Name ='"+textBox1.Text+"', U_Pass = '" +textBox2.Text+"', U_Type = 1 FROM tblUsers",con);


            con.Open();
            SqlDataReader sdr = command.ExecuteReader();


            if ("@type"==1)
            {
                MessageBox.Show("Login Successful");
                MDIParent1 settingsForm = new MDIParent1();
                settingsForm.Show();
                this.Hide();
            }
            else
            {
                MessageBox.Show("Login Successful");
                MDIParent2 settingsForm = new MDIParent2();
                settingsForm.Show();
                this.Hide();
            }
        }

我真的不知道它的正确语法。请帮助我,我真的很感激。谢谢

2 个答案:

答案 0 :(得分:2)

你大致有正确的想法,但你的实施已经完成。

您在发送SQL查询之后但在检查结果之前验证了文本框,并且您还传递了用户的类型。

用户类型应与用户一起存储在数据库中,您可以返回匹配行的用户类型(基于用户名和密码)。而且你的语法在某些地方已经过时了。

基于您似乎正在做的事情的简化方法将是这样的:

在执行命令之前对文本框进行验证。如果验证通过,则选择与用户名和密码匹配的行,并相应地处理结果:

private void button1_Click(object sender, EventArgs e)
{

    bool validInput = false;

    if (!String.IsNullOrWhitespace(textBox1.Text))
    {
        validInput = true;
    }
    else
    {
        MessageBox.Show("Please enter a user name.");
    }
    if (!String.IsNullOrWhitespace(textBox2.Text))
    {
        validInput = true;
    }
    else
    {
        MessageBox.Show("Please enter a password.");
    }

    if (validInput)
    {
        using (SqlConnection conn = new SqlConnection("Data Source=MJ-PC\\SQLEXPRESS;Initial Catalog=Users;Integrated Security=True"))
        {
            conn.Open();
            SqlCommand command = new SqlCommand("SELECT * FROM tblUsers WHERE U_Name = @U_Name AND U_Pass = @U_Pass", conn);
            command.Parameters.Add("@U_Name", SqlDbType.VarChar).Value = textBox1.Text;
            command.Parameters.Add("@U_Pass", SqlDbType.VarChar).Value = textBox2.Text;

            using (SqlDataReader reader = command.ExecuteReader())
            {

                if (reader.HasRows)
                {
                    reader.Read();
                    string userType = reader["U_type"].ToString();
                    if (userType == "1")
                    {
                        // Handle regular users
                    }
                    else if (userType == "2")
                    {
                        // Handle admin users
                    }

                }
                else
                {
                    MessageBox.Show("Login failed.");
                }
            }
        }
    }
}

上面的代码说明了这种方法。如果两个文本框中都包含文本,则validInput标记设置为true。然后打开连接,设置命令和参数,执行命令并返回读取器。如果阅读器有行(意味着找到与用户名和密码匹配的1个或多个记录),reader将前进到第一个记录(对于给定的用户名/密码组合,应该只有一个匹配)。

询问“U_type”列以查看它是普通用户还是管理员用户,并相应地处理用户。

从您发布的代码中不清楚“U_type”是字符串还是整数;如果它是一个整数,你需要像这样转换它:

int userType = Convert.ToInt32(reader["U_type"]);

并更改相应的if检查:

if (userType == 1)

if (userType == 2)

答案 1 :(得分:1)

如果要对用户进行身份验证并比较Type,则返回DataTable。

 public DataTable ValidateUser(string username,string password)
    {
        DataTable dt = new DataTable();
        SqlCommand cmd; SqlDataReader dr;
        SqlConnection con = new SqlConnection(yourConnectionString);
        try
        {
            cmd = new SqlCommand();
            cmd.CommandText = "Select * from tblUsers where U_Name=@U_Name and U_Pass=@U_Pass";
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@U_Name", username);
            cmd.Parameters.AddWithValue("@U_Pass", password);
            cmd.Connection = con;
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            dr = cmd.ExecuteReader();
            dt.Load(dr);
        }
        catch (Exception ex)
        {
            dt = null;

        }
        finally
        {
            if (con.State != ConnectionState.Closed)
            {
                con.Close(); con.Dispose();
            }
        }
        return dt;
    }

调用ValidateUser方法:

DataTable dt=new DataTable();
dt=ValidateUser();
if(dt!=null && dt.Rows.Count>0)
{
    if(Convert.ToInt32(dt.Rows.[0]["U_Type"])==1)
    {
       //show form for user where utpe=1
    }
    else if(Convert.ToInt32(dt.Rows.[0]["U_Type"])==2)
   {
       //show form for user where utype=1
    }
    else
    {
       //otherstuff
    }
}
else
{
 //invwalid user
}

希望这有帮助