2016-08-17 88 views
-1

在我的web表單中,我有2個只能接受數字的字段(它們的值的計算結果應該顯示在第三個字段中,這兩個字段的RegularValidation在用戶點擊提交按鈕之前工作正常,但不是如何處理它在webform中驗證

<asp:TextBox ID="TextBox1" runat="server" placeholder="Liter"></asp:TextBox><span style="color:red;font-weight:bold"> *</span> 
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="This is required" ForeColor="Red" ValidationGroup="test" ControlToValidate="TextBox1" Display="Dynamic"></asp:RequiredFieldValidator> 
    <asp:RegularExpressionValidator ID="RegularExpressionValidator2" ControlToValidate="TextBox1" runat="server" ForeColor="red" ErrorMessage="Enter only numbers!" ValidationExpression="\d+" Display ="Dynamic"></asp:RegularExpressionValidator> 

提交按鈕:

protected void btn_Click(object sender, EventArgs e) 
{ 
    if (Page.IsValid) 
    { 
      TextBox3.Text = ((Convert.ToInt32(TextBox1.Text) * 4.18 * Convert.ToInt32(TextBox2.Text))/3600).ToString(); 
      double result = Convert.ToDouble(TextBox3.Text); 
      TextBox3.Text = String.Format("{0:0.00}", result); 
+1

的可能的複製[?如何讓一個文本框僅整數(http://stackoverflow.com/questions/9732455/how-to-allow-only-integers-in-a -textbox) – techspider

+0

不......它完全不同於此 – Biju

回答

0

你可以寫一個函數/方法這樣通過文本框的值

public static bool isNumeric(string val, System.Globalization.NumberStyles NumberStyle) 
{ 
    Int32 result; 
    return Int32.TryParse(val, NumberStyle, 
     System.Globalization.CultureInfo.CurrentCulture, out result); 
} 

呼叫並檢查例如該方法通過以下

var _isNumeric2 = isNumeric("9.", System.Globalization.NumberStyles.Integer); 

與TextBox3.Text值

+0

感謝@MethodMan,但TextBox1和TextBox2應該被檢查! – Biju

+0

然後進行檢查/調用適當有幾種方法來處理這個如果這個工程,然後將其標記爲可接受的答案..你可以改變方法來處理任何文本值 – MethodMan

0

所有需要更換第一paramtere是添加ValidationGroup="test"相同場。解決的辦法是:

<asp:TextBox ID="TextBox1" runat="server" placeholder="Liter"></asp:TextBox><span style="color:red;font-weight:bold"> *</span> 
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="This is required" ForeColor="Red" ValidationGroup="test" ControlToValidate="TextBox1" Display="Dynamic"></asp:RequiredFieldValidator> 
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" ControlToValidate="TextBox1" runat="server" ForeColor="red" ErrorMessage="Enter only numbers!" ValidationExpression="\d+" ValidationGroup="test" Display ="Dynamic"></asp:RegularExpressionValidator>