ASP.NET从数据库中读取

时间:2013-05-12 13:25:40

标签: asp.net

这是问题所在:

如果值与TextBox2.TextLabel2.Text中的值相同,我想这样做,我不会被重定向到下一页但是我会被要求输入不同的文本。这是我的代码:

protected void Button1_Click(object sender, EventArgs e)
{
   con.Open();
   SqlCommand cmd = new SqlCommand();
   cmd.Connection = con;
   cmd = new SqlCommand("SELECT Question FROM Animals WHERE Question = @Question", con);
   cmd.Parameters.AddWithValue("@Question", Label2.Text);
   cmd.ExecuteNonQuery();
   dr = cmd.ExecuteReader();

   if (dr.Read())
   {
      Response.Write("Enter different question");
   }
   else
   {
      if(dr[0].ToString() != TextBox2.Text)
         Session["question"] = Label2.Text;
         Session["Animal3"] = TextBox1.Text;
         Session["Question2"] = TextBox2.Text;
         Session["Animal2"] = Label3.Text;
         Session["Animal"] = Label4.Text;

         Response.Redirect("~/StartGame2.aspx");
   }

2 个答案:

答案 0 :(得分:0)

您可以在TextBox2上使用CompareValidator

<asp:CompareValidator
        id="Validator1" 
        ControlToValidate="TextBox2" 
        ControlToCompare="Label2" 
        Type="String"
        Text="Enter different text." 
        runat="server" />

答案 1 :(得分:0)

尝试用以下方法替换您的方法:

     protected void Button1_Click(object sender, EventArgs e)
     {
        con.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        cmd = new SqlCommand("SELECT Question FROM Animals WHERE Question = @Question", con);
        cmd.Parameters.AddWithValue("@Question", Label2.Text);
        cmd.ExecuteNonQuery();
        dr = cmd.ExecuteReader();

        if (dr.Read())
        {
           if (dr[0].ToString() == TextBox2.Text)
           {
              Response.Write("Enter different question");
              return;
           }
        }

        Session["question"] = Label2.Text;
        Session["Animal3"] = TextBox1.Text;
        Session["Question2"] = TextBox2.Text;
        Session["Animal2"] = Label3.Text;
        Session["Animal"] = Label4.Text;

        Response.Redirect("~/StartGame2.aspx");

     }