如何使用asp.net,c#,adonet在两个文本字段中检查用户输入的数据是否正确

时间:2022-09-23 19:58:44

I have two text fields emplastname and empnumber. I want to take values from user. and check with the database values. If match..redirect to next page. else stop him.

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

I tried this

我试过这个

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();

How better and efficiently we can do this?

我们能做得更好,更有效率吗?

1 个解决方案

#1


2  

First of all for selecting record use ExecuteReader, like this:

首先选择记录使用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}
   }
}

#1


2  

First of all for selecting record use ExecuteReader, like this:

首先选择记录使用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}
   }
}