2013-05-17 35 views
0

在这里我想验证用户通过使用离开事件功能输入的数据,所以我想在这里做的是匹配用户在数据库中输入的数据。我是通过在这里使用这个代码来做到的,但我不确定我是否正确地做了这件事。我试图运行它,但它不起作用。将在组合框中输入的数据与数据库匹配

private void cboBranch_Leave(object sender, EventArgs e) 
{ 

    if (cboBranch.Text.Length > 0) 
    { 
     try 
     { 
      using (MySqlConnection con = new MySqlConnection(serverstring)) 
      { 
       string query = "SELECT * FROM tblBranches WHERE [email protected]"; 

       con.Open(); 
       using (MySqlCommand cmd = new MySqlCommand(query, con)) 
       { 
        using (MySqlDataReader dr = cmd.ExecuteReader()) 
        { 
         cmd.Parameters.Add("@branch", MySqlDbType.VarChar, 30).Value = cboBranch.Text; 

         int count = 0; 
         bool flag = false; 

         while (dr.Read()) 
         { 
          count++; 
          if (count == 1) 
          { 
           flag = true; 
          } 
         } 

         if (flag == false) 
         { 
          MessageBox.Show("The Branch name you entered does not match.", "AFICIONADO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
      cboBranch.Select(); 
         } 
        } 

       } 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 

    } 
} 

回答

0

您可以使用SELECT COUNT(*)....从您的表中获取计数,又你attching参数的命令之前执行你的命令。例如:

private void cboBranch_Leave(object sender, EventArgs e) 
{ 
    if (cboBranch.Text.Length > 0) 
    { 
     try 
     { 
      using (MySqlConnection con = new MySqlConnection(serverstring)) 
      { 
       string query = "SELECT count(*) FROM tblBranches WHERE [email protected]"; 
       con.Open(); 
       using (MySqlCommand cmd = new MySqlCommand(query, con)) 
       { 

        cmd.Parameters.Add("@branch", MySqlDbType.VarChar, 30).Value = cboBranch.Text; 

        //Use ExecuteScalar 
        int count = Convert.ToInt32(cmd.ExecuteScalar()); 
        if (count <= 0) 
        { 
         MessageBox.Show("The Branch name you entered does not match.", "AFICIONADO", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
         cboBranch.Select(); 
        } 
       } 

      } 
     } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 

    } 
} 
相关问题