0

我有两个文本字段 emplastname 和 empnumber。我想从用户那里获取价值。并检查数据库值。如果匹配..重定向到下一页。否则阻止他。

我试过这个

protected void btn_Submit_Click(object sender, EventArgs e)
        {
            if(String.IsNullOrEmpty(txt_LastName.Text) && (String.IsNullOrEmpty(txt_EmployeeNumber.Text))) 
            {
            //Response.Redirect("~/default.aspx");
            string connectionString = "Data Source=;initial catalog= ; User ID=sa;Password=;Integrated Security=true;";

             string query = "select n.LastName, u.EmployeeNumber from  .[dbo].[EPCN_Users] u join  [dbo]. [EmployeeNames] n on n.UserID = u.ID where n.LastName = @lastName and u.EmployeeNumber = @employeeNumber "; 
           // create connection and command
        using(SqlConnection cn = new SqlConnection(connectionString))
      using(SqlCommand cmd = new SqlCommand(query, cn))
       {
        // define parameters and their values

        cmd.Parameters.Add("@Lastname", SqlDbType.VarChar, 50).Value = txt
        cmd.Parameters.Add("@EmployeeNumber", SqlDbType.VarChar, 50).Value = employeeNumber;



        cn.Open();
        cmd.ExecuteNonQuery();
        cn.Close();

我们可以如何更好、更有效地做到这一点?

4

1 回答 1

2

首先选择记录使用ExecuteReader,像这样:

using(SqlConnection cn = new SqlConnection(connectionString))
{
   using(SqlCommand cmd = new SqlCommand(query, cn))
   {
     // define parameters and their values
     cmd.Parameters.Add("@Lastname", SqlDbType.VarChar, 50).Value = txt
     cmd.Parameters.Add("@EmployeeNumber", SqlDbType.VarChar, 50).Value =employeeNumber;

     SqlDataReader reader = null;
     reader = cmd.ExecuteNonQuery();
     DataTable table = new DataTable();
     table.Load(reader);

      if (!reader.IsClosed)
      {
         reader.Close();
      }
      if (table.Rows.Count > 0)
      {
         // redirect 
      }
      else { //error message}
   }
}
于 2013-10-24T21:47:54.593 回答