日期:2014-05-18  浏览次数:20901 次

不同账号登陆不同的窗体界面。
代码已经写好了,可是怎么没有办法验证密码和用户名啊
代码如下:请各位大侠帮忙

string sql = "Server = localhost;DataBase=denglu;Integrated Security=true;user ID=sa;password=";
  SqlConnection sqlcon = new SqlConnection(sql);
  sqlcon.Open();
  SqlCommand cmd = new SqlCommand("select * from denglu where name='" + textBox1.Text + "'and mi='" + textBox2.Text + "'", sqlcon);
  //cmd.Connection = sqlcon;
  //cmd.CommandText = "select * from denglu where name='" + textBox1.Text + "'and mi='" + textBox2.Text + "'";
  //cmd.CommandType = CommandType.Text;
  //SqlDataReader sqlread = cmd.ExecuteReader();
   
  SqlDataAdapter sqlAdapter = new SqlDataAdapter(cmd);
  DataSet set = new DataSet();
  //sqlread.Close();
  sqlAdapter.Fill(set);
  DataTable myTable = set.Tables[0];
  DataRow rowt = myTable.Rows[0];
   
   
  if (textBox1.Text.Trim() == "")
  {
  MessageBox.Show(null, "用户名不能为空", "登陆失败", MessageBoxButtons.OK, MessageBoxIcon.Question);
  return;
  }

  else if (( rowt["name"].ToString()==textBox1.Text)&&( rowt["mi"].ToString ()== textBox2.Text))
  {
   
   
  if (rowt["pow"].ToString() == "a")
  {
  this.DialogResult = DialogResult.OK;
  //Form1 f1 = new Form1();
  this.Close();
  }
  else if (rowt["pow"].ToString() == "b")
  {
  Form4 f4 = new Form4();
  f4.Show();
  this.Close();
  }
  sqlcon.Close();


  }
  else
  {
  MessageBox.Show("用户名或密码不正确");
  textBox1.Focus();
  }

------解决方案--------------------
流程这样,先判断 用户名 和 密码 的文本框是否为空,再请求数据库,执行你上面的 sql 得到 DataTable ,判断 DataTable 行数,如果是 0 就是用户名密码错误,如果大于 0 就取得第一行的 pow 列的值,判断后选择打开相应的窗体。
------解决方案--------------------
C# code
if (textBox1.Text.Trim() == "")
{
    MessageBox.Show(null, "用户名不能为空", "登陆失败", MessageBoxButtons.OK, MessageBoxIcon.Question);
    return;
}

if (textBox2.Text.Trim() == "")
{
    MessageBox.Show(null, "密码不能为空", "登陆失败", MessageBoxButtons.OK, MessageBoxIcon.Question);
    return;
}

string sql = "Server = localhost;DataBase=denglu;Integrated Security=true;user ID=sa;password=";
DataTable dtbl = new DataTable();
SqlConnection sqlcon = new SqlConnection(sql);
sqlcon.Open();
SqlDataAdapter sqlAdapter = new SqlDataAdapter("select * from denglu where name='" + textBox1.Text + "'and mi='" + textBox2.Text + "'", sqlcon);
sqlAdapter.Fill(dtbl);
sqlAdapter.Dispose();
sqlcon.Dispose();

if (dtbl.Rows.Count > 0)
{
    switch (dtbl.Rows[0]["pow"].ToString())
    {
        case "a":
            {
                // 打开 a 的
                break;
            }
        case "b":
            {