private void btnYes_Click(object sender, EventArgs e)
{
if(this.txtUserName.Text=="")
{
MessageBox.Show("用户名不能为空!");
this.txtUserName.Focus();
return;
}
else
{
if(this.txtUserPwd.Text=="")
{
MessageBox.Show("密码不能为空!");
this.txtUserPwd.Focus();
return;
}
else
{
string sql = "select userPwd from users where userName='"+this.txtUserName.Text.Trim()+"'";
SqlConnection con = DB.createSqlConnection();//创建了一个DB.cs里面的函数createSqlconnection.这里没有错误 con.Open();
SqlDataAdapter da = new SqlDataAdapter(sql,con);
DataSet ds = new DataSet();
try
{
da.Fill(ds, "operator");
}
catch (Exception)
{
MessageBox.Show("未能成功连接数据库");
}
if (ds.Tables["operator"].Rows[0][2].ToString() == this.txtUserPwd.Text.Trim())//if语句这行出现的错误:无法找到列 2 {
MessageBox.Show("登陆成功!");
}
else
{
MessageBox.Show("密码输入错误!");
}
}
}
}错误:无法找到列 2
{
if(this.txtUserName.Text=="")
{
MessageBox.Show("用户名不能为空!");
this.txtUserName.Focus();
return;
}
else
{
if(this.txtUserPwd.Text=="")
{
MessageBox.Show("密码不能为空!");
this.txtUserPwd.Focus();
return;
}
else
{
string sql = "select userPwd from users where userName='"+this.txtUserName.Text.Trim()+"'";
SqlConnection con = DB.createSqlConnection();//创建了一个DB.cs里面的函数createSqlconnection.这里没有错误 con.Open();
SqlDataAdapter da = new SqlDataAdapter(sql,con);
DataSet ds = new DataSet();
try
{
da.Fill(ds, "operator");
}
catch (Exception)
{
MessageBox.Show("未能成功连接数据库");
}
if (ds.Tables["operator"].Rows[0][2].ToString() == this.txtUserPwd.Text.Trim())//if语句这行出现的错误:无法找到列 2 {
MessageBox.Show("登陆成功!");
}
else
{
MessageBox.Show("密码输入错误!");
}
}
}
}错误:无法找到列 2
string sql = "select userPwd from users where userName='"+this.txtUserName.Text.Trim()+"'";
而判断时你取的是第二列,因为表中只有一列所以报错:
if (ds.Tables["operator"].Rows[0][2].ToString() == this.txtUserPwd.Text.Trim
我还想我问的是,除了这样的写法,还有其他if方式吗?
用这个方法cmd.ExecuteScalar();
检索第一行第一列,然后判断就可以了
不用SqlDataAdapter 和ds了
SqlConnection con = DB.createSqlConnection();//创建了一个DB.cs里面的函数createSqlconnection.这里没有错误 con.Open();
SqlCommand com=new SqlCommand(sql,con);
SqlDataReader read= com.ExecuteReader();
try
{
while(read.Read())
{
if(read["userPwd"].ToString()==txtUserPwd.Text.Trim())
MessageBox("OK");
}
}
catch (Exception)
{
MessageBox.Show("未能成功连接数据库");
}