这是在登录时的一段代码,当运行到userName = reader.GetValue(2).ToString();时会错先错误提示“在没有任何数据时进行无效的读取尝试”。为什么啊?哪错了啊?
private void btnOK_Click(object sender, EventArgs e)
        {
            string userName = string.Empty, password = string.Empty;
            
            SqlCommand sqlcomm = new SqlCommand("select * from Worker where WorkerLogin='" +textBox1.Text + "'",da.link());// 
            
            SqlDataReader reader = sqlcomm.ExecuteReader();
            reader.Read();            
            userName = reader.GetValue(2).ToString();
            password = reader.GetValue(3).ToString();
            if (userName==textBox1.Text)
            {
                if (password==textBox2.Text)
                {
                    MessageBox.Show("用户名及密码正确。", "提示");
                    SqlCommand sqlcomm1 = new SqlCommand("insert SystemEvent" + "(EventDepict,EventHappenTime)" +
                        "values(@EventDepict,@EventHappenTime)", da.link());
                    sqlcomm1.Parameters.AddWithValue("@EventDepict", "用户" + textBox1.Text + "登录");
                    sqlcomm1.Parameters.AddWithValue("@EventHappenTime", DateTime.Now.ToString());
                    sqlcomm1.ExecuteNonQuery();
                    this.Close();
                    FormSystemGuanli form = new FormSystemGuanli();
                    form.ShowDialog();
                }
                else
                {
                    MessageBox.Show("密码错误!", "提示框", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    label2.Text = "";
                }
            }
            else
            {
                MessageBox.Show("登录名错误!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                label2.Text = "";
            }
        }

解决方案 »

  1.   

    1、看看连接有没有打开;
    2、          reader.Read();            
                userName = reader.GetValue(2).ToString(); 
                password = reader.GetValue(3).ToString(); 
    改为:
    if(reader.read())
    {
                userName = reader.GetValue(2).ToString(); 
                password = reader.GetValue(3).ToString(); 
    }
      

  2.   

    1)数据库连接为打开……
    貌似楼主没有建立SqlConnection
    而且DA看不出是什么……
    da.link()不懂是什么……2)要确定是否存在数据……如果为NULL则不能使用TOSTRING()3)如果只是判断是否登陆你可以试试这个方法
    select * from Worker where WorkerLogin='**' and name='****' and password='***'然后判断
    if(reader.Read())//或者if(reader.HasRows!=0)
    {
    登陆成功
    }
    else
    {
    登陆失败
    }个人感觉这个好一点。
      

  3.   

    还有,最好是把reader.GetValue(2),改为列名..
    并且,我觉得有点逻辑错误,你直接在sql里面把用户名和密码都当成条件加进去,然后,if(reader.read()){}直接写就是了,不用再来两个if.
      

  4.   

    在读取表中列值的时候,我改成了if(reader.read()){};这时,读取的用户名和表中设置的用户名匹配上了,但是到运行到sqlcomm1.ExecuteNonQuery()时,出现如下的错误提示:“无法将 NULL 值插入列 'EventID',表 'WorkerManget.dbo.SystemEvent';该列不允许空值。INSERT 失败。语句已终止。”
    SystemEvent是表名,只是想记录一下登录情况,然后将登录情况插入到SystemEvent中。
    为什么会出现上面的情况啊?