这是在登录时的一段代码,当运行到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 = "";
}
}
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 = "";
}
}
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();
}
貌似楼主没有建立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
{
登陆失败
}个人感觉这个好一点。
并且,我觉得有点逻辑错误,你直接在sql里面把用户名和密码都当成条件加进去,然后,if(reader.read()){}直接写就是了,不用再来两个if.
SystemEvent是表名,只是想记录一下登录情况,然后将登录情况插入到SystemEvent中。
为什么会出现上面的情况啊?