2014-02-28 67 views
0

有人可以幫我糾正這段代碼嗎? 對不起我的英文不好,我是荷蘭人。運算符'>'不能應用於類型'System.Web.UI.WebControls.TextBox'和'int'的操作數

我的HTML:

<asp:Label ID="Label1" runat="server" Font-Bold="True" Font-Size="XX-Large" 
    Text="Inloggen"></asp:Label> 
    <br /> 
    <br /> 
    <asp:Label ID="Label2" runat="server" Text="Voornaam"></asp:Label> 
    <br /> 
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
    <br /> 
    <br /> 
    <asp:Label ID="Label3" runat="server" Text="Wachtwoord"></asp:Label> 
    <br /> 
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> 
    <br /> 
    <br /> 
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Login" /> 

我aspx.cs

TextBox Textbox1 = new TextBox(); 

    if ((TextBox1 < 3) || (TextBox1 > 15)) 
     { 

     } 
    else 
     { 

     } 

我希望有人能幫助我

+0

而且你想比較文本框或進入文本框中的數值文本的長度 - 說明你想實現可真正有用的東西。 –

回答

0

您與3是int比較TextBox類型的TextBox1的。 TextBox和int無法進行比較。事實上,你想比較文本框的值與int。g文本屬性爲string你應該使用int.Parse將其轉換爲int來與3進行比較。也||運營商的操作數應該是boolean

if (int.Parse(TextBox1.Text) < 3) || int.Parse(TextBox1 > 15)) 
{ 

} 
else 
{ 

} 
0

使用

int a = int.Parse(Textbox1.Text); 
if(a = < 3 || a > 15) 
0

你不能用文本框比較本身comapre其文本值

if ((Convert.ToInt32(TextBox1.Text) < 3) || ((Convert.ToInt32(TextBox1.Text) > 15)) 
     { 

     } 
    else 
     { 

     } 
+0

當然,比較字符串和數字會引發另一個異常 – Steve

+0

@Steve是我添加了一個轉換 – Rex

0

問題是你正在嘗試將文本框與數字進行比較。不是它的價值。解決方案:

int n1=ConvertToInt32(TextBox1.Text); 
if(n<3 || n>15) 
... 

不要忘記只允許輸入數字或它會引發錯誤。爲了避免它:

try{ 
int n1=ConvertToInt32(TextBox1.Text); 
    if(n<3 || n>15) 
    ... 
} catch { 
//here you can do what you want to do if weird input is given 
} 
+0

輸入字符串格式不正確。你能解決這個問題嗎? – VeraRodermond

0

用於從文本框中提取用戶輸入的屬性是Text屬性。

但處理時,數量預計將用戶輸入的唯一正確途徑就是通過數據類型的TryParse方法

TextBox Textbox1 = new TextBox(); 
.... 

int num; 
if(Int32.TryParse(TextBox1.Text, out num) 
{ 
    // TryParse returns true, we have the number 
    if(num < 3 || num > 15) 
    { 

    } 
    else 
    { 

    }  
} 
else 
    // TryParse returns false, the input text is not a integer number 
    ... message to your user... "we need a number, not something else" 

Int.Parse或Convert.ToInt32不被這裏使用,因爲它們會引發如果您的用戶在文本框中鍵入類似於某個詞的內容,而不是有效的數字,則爲例外。

我當然不應該忘記提及,有在Validation controls

相關問題