1

I am trying to make a windows Form Application with a login screen,Form3 Will open Form1 if the username and password are correct.

The code is linked to a database

The code is as follows:

 private void button1_Click(object sender, EventArgs e)
 {
            string u_id = textBox1.Text;
            string u_pwd = textBox2.Text;

            SqlConnection conn = new SqlConnection("Data Source=mmtsql.XXX.XXXXX.ac.uk;Initial Catalog=mmt12-186;User ID=XXXXXX;Password=XXXXXX");
            conn.Open();

            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = ("SELECT * FROM UsersData WHERE User = '" + textBox1.Text + "'");
            cmd.Parameters.AddWithValue("un", u_id);

            SqlDataReader reader = cmd.ExecuteReader();

            if (reader.Read() == false)
            { 
                    label3.Text = "Invalid Username or Password !";
                    return;
            }

            string realpwd = reader.GetString(0);

            if (u_pwd == realpwd)
            {
                    Form1 formload = new Form1();
                    formload.Show();
            }
}

Every time I run this code, I get an exception on with the line:

string realpwd = reader.GetString(0);

The exception is:

Invalid attempt to read when no data is present.

The UsersData table has 3 columns, Id, User, Password

Thanks goes to "Alfred Sanz" who answered the question, the problem now is that no error is present but no data is shown, as if the button1_click has no method, the current code is:

    private void button1_Click(object sender, EventArgs e)
    {
        string u_id = textBox1.Text;
        string u_pwd = textBox2.Text;
        SqlConnection conn = new SqlConnection("Data Source=mmtsql.XX.XXX.ac.uk;Initial Catalog=XXXXXXX ;User ID=XXXX;Password=XXXXX");
        conn.Open();
        SqlCommand cmd = conn.CreateCommand();
        cmd.CommandText = ("SELECT * FROM UsersData WHERE User = @un");
        cmd.Parameters.AddWithValue("@un", u_id);
        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
            if (reader["Password"].ToString() == u_pwd)
            {
                Form1 formload = new Form1();
                formload.Show();
            }
            else
            {
                label3.Text = "Invalid Username or Password !";
            }

    }
4

1 回答 1

0

您已经将valueUSER 设置为,'" + textBox1.Text + "'"但您还设置了一个cmd.Parameters.AddWithValue("un", u_id);确实不存在的值,请将您的代码更改为

            cmd.CommandText = "SELECT * FROM UsersData WHERE User = @un";
            cmd.Parameters.AddWithValue("@un", u_id);

您还可以将阅读器部分更改为:

while (reader.Read())
{
    if (reader["Password"].ToString() == u_pwd.Text
        {
              Form1 formload = new Form1();
              formload.Show();
        }
    else
      {
        label3.Text = "Invalid Username or Password !";
      }
}
于 2013-03-09T01:24:33.470 回答