2013-05-12 45 views
0

閱讀的問題:ASP.NET從數據庫

我想讓如果值相同那就是TextBox2.TextLabel2.Text,我不會重定向到下一個頁面,而是我會要求輸入不同text.Here是我的代碼:

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"); 
    } 
+0

不清楚你想做什麼。 – 2013-05-12 13:35:45

+0

什麼是'TextBox2','Label2'? ,請詳細解釋 – 2013-05-12 13:37:15

+0

如果textbox2中的數據等於label2(它已經存儲在數據庫中),它會抱怨它,並要求輸入不同的數據。 – 2013-05-12 13:38:22

回答

0

可以使用CompareValidator上TextBox2中

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

沒有工作 – 2013-05-12 13:47:45

+0

工作示例 - > http://www.w3schools.com/aspnet/showaspx.asp?filename=demo_comparevalidator – 2013-05-12 13:56:38

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

    } 
+0

無數據存在時嘗試讀取無效。 – 2013-05-12 15:50:38

+0

對不起,請參閱我的編輯。 – jomsk1e 2013-05-12 16:02:50

+0

欣賞@JRC的努力,但我解決了我的問題。 – 2013-05-12 16:10:51