简体   繁体   English

针对SQL DB的C#Windows窗体应用程序文本框验证

[英]C# Windows Forms Application textbox validation against SQL DB

I'm new to C# and have a background in SQL so apologies if this is a very stupid query, but I have been trawling google for about 2 hours now and can't find what I need. 我是C#的新手,并且有SQL的背景,如果这是一个非常愚蠢的查询,我很抱歉,但我现在已经拖网谷歌大约2个小时了,找不到我需要的东西。 If someone knows of an article they can point me to, that would be great. 如果有人知道他们可以指向我的文章,那就太好了。

I have a simple windows forms application, and I'm setting up a login box so that users have to enter their user ID to proceed. 我有一个简单的Windows窗体应用程序,我正在设置一个登录框,以便用户必须输入他们的用户ID才能继续。

I have a SQL Server DB (SQL 2005) with the following table: 我有一个SQL Server数据库(SQL 2005)与下表:

Users UserID (int); 用户UserID(int); userName nvarchar(50) userName nvarchar(50)

I am using Visual Studio 2010 我正在使用Visual Studio 2010

What I'm stymied by is how to check whether their userID exists in my SQL Table (called users...) I'm not going to put any code here because it's been rewritten from scratch so many times that a clean slate is probably best! 我遇到的问题是如何检查他们的用户ID是否存在于我的SQL表中(称为用户...)我不会在这里放任何代码,因为它已经从头开始重写了很多次,可能是一个干净的平板最好!

Ideally, I want the user to enter their user ID, and click 'login'. 理想情况下,我希望用户输入他们的用户ID,然后单击“登录”。 When they do this, if their userID is not valid in the DB table then I need it to give an error msgBox; 当他们这样做时,如果他们的userID在DB表中无效,那么我需要它来给出错误msgBox; if it is valid then it should log them in, passing their userID and userName (stored in the DB table) to a variable which I can use elsewhere in the application to populate fields. 如果它是有效的,那么它应该记录它们,将它们的userID和userName(存储在DB表中)传递给一个变量,我可以在应用程序的其他地方使用它来填充字段。

I hope this makes sense, and I'm sure I've missed the perfect article out there which will explain it all - hopefully one of you kind people can point me in the right direction! 我希望这是有道理的,我相信我已经错过了那些可以解释一切的完美文章 - 希望你们中的一个善良的人能指出我正确的方向!

Thank you 谢谢

    /*table code
     * create table login
           (
                id varchar(25),
                    pass varchar(25)
            )   
     * 
     * 
     * 
     * 
     */

    string Connectstring = @"Data Source=DELL-PC;Initial Catalog=stud;Integrated Security=True";
    public Form1()
    {
        InitializeComponent();
    }



    private void button1_Click(object sender, EventArgs e)
    {
        SqlConnection cn = new SqlConnection(Connectstring);
        cn.Open();


        SqlCommand cmd = new SqlCommand("select * from log where id=@a and pass=@b", cn);
        cmd.Parameters.AddWithValue("@a", textBox1.Text.ToString().ToUpper());
        cmd.Parameters.AddWithValue("@b", textBox2.Text);

        SqlDataReader dr = cmd.ExecuteReader();


        if ((dr.Read() == true))
        {
            MessageBox.Show("The user is valid!");
            Form2 mainForm = new Form2();
            mainForm.Show();
            this.Hide();
        }
        else
        {
            MessageBox.Show("Invalid username or password!");
        }


    }

You should make a simple SQL query with the userID the user entered, like 您应该使用用户输入的userID进行简单的SQL查询,例如
SELECT UserID from Users where userID= value. 从userID = value的用户中选择UserID。 The executeNonQuery() will return the number of matches. executeNonQuery()将返回匹配数。 If the returned value ==1, means that the userid exists in the database. 如果返回值== 1,则表示该用户标识存在于数据库中。 If the returned value is different from 1, means that the userid not exists or it was registered multiple times. 如果返回值与1不同,则表示userid不存在或已多次注册。 So, if is 1 then you cand call a different form to make different things, else you call anoter form or output a messagebox with an error message 所以,如果是1,那么你可以调用另一种形式来制作不同的东西,否则你调用anoter形式或者输出一个带有错误消息的消息框

Declare a connection string to Your database 声明您的数据库的连接字符串

string connString = @"Data Source=.\SQLEXPRESS;Initial Catalog=YourDatabase;Integrated Security=True";

After this You can use a validate method below 在此之后您可以使用下面的验证方法

private bool ValidateUserById(string connString, int id)
{
    using (var conn = new SqlConnection(connString))
    {
        conn.Open();

        var sqlString = string.Format("Select * From Users where Id = {0}", id);
        using (var cmd = new SqlCommand(sqlString, conn))
        {
                return cmd.ExecuteScalar() != null;
        }
    }
}

Then on button click You can check the user 然后单击按钮您可以检查用户

if (ValidateUserById(connString, Convert.ToInt32(textBox1.Text)))
{
    //..
}
else
{
    //..
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM