我是 C# 的新手。我有不同文本框的代碼塊。我決定為此代碼創建類以在不同的 Windows 表單中使用。
這是我的 Windows 表單代碼
using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace POS.screens
{
public partial class sell : MetroFramework.Forms.MetroForm
{
ConnectionClass cons = new ConnectionClass();
FillComboBox fcb = new FillComboBox();
{
InitializeComponent();
}
public void PriceTextBox_TextChanged(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(QuantityTextBox.Text) || String.IsNullOrEmpty(PriceTextBox.Text))
{
TotalTextBox.Text = 0.ToString();
}
else
{
fcb.CheckNumbersOnly(PriceTextBox);
int Quantity = Convert.ToInt32(QuantityTextBox.Text);
decimal Price = Convert.ToDecimal(PriceTextBox.Text);
decimal Total = Price * Quantity;
TotalTextBox.Text = Total.ToString();
}
}
}
}
這是類代碼
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace POS
{
class FillComboBox
{
ConnectionClass cons = new ConnectionClass();
public void CheckNumbersOnly(dynamic TextBoxName)
{
if (!Regex.IsMatch(TextBoxName.Text, @"[0-9] (\.[0-9][0-9]?)?") && (TextBoxName.Text != ""))
{
MessageBox.Show(TextBoxName.Text);
return;
}
if (!decimal.TryParse(TextBoxName.Text, out decimal PriceValue))
{
MessageBox.Show("Please Enter Correct Number");
TextBoxName.Clear();
return;
}
}
}
}
一切正常但回傳陳述句不起作用。如果用戶插入一個字母或不正確的數字。程式應該顯示訊息并停止進一步作業,但它不會停止。它顯示訊息并運行下一條陳述句并給出錯誤。
當我直接使用此代碼而不創建類時它作業正常。我認為,我在課堂上使用 return 陳述句的方式是錯誤的。我是新學習者。提前致謝。
uj5u.com熱心網友回復:
有很多方法可以做到這一點,一個簡單的CheckNumbersOnly方法是讓您的方法回傳一個布林值。也可能更好地重命名它(為了便于閱讀),然后在PriceTextBox_TextChanged方法中,您將檢查回傳是否為真,只有在它為真時才繼續。
把它放在一起:
驗證碼:
public bool NumbersAreValid(string value)
{
if (!Regex.IsMatch(value, @"[0-9] (\.[0-9][0-9]?)?") && (value != ""))
{
//Note: this isn't a very good error message, and the above Match
// check seems to redo the work of `TryParse` bellow
MessageBox.Show(value);
//Let caller know this failed validation
return false;
}
if (!decimal.TryParse(value, out decimal PriceValue))
{
MessageBox.Show("Please Enter Correct Number");
return false;
}
return true;
}
表格代碼:
public void PriceTextBox_TextChanged(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(QuantityTextBox.Text) || String.IsNullOrEmpty(PriceTextBox.Text))
{
TotalTextBox.Text = 0.ToString();
}
else
{
//When NumbersAreValid returns false, this if statement ends processing
if (!fcb.NumbersAreValid(PriceTextBox.Text)) return;
int Quantity = Convert.ToInt32(QuantityTextBox.Text);
decimal Price = Convert.ToDecimal(PriceTextBox.Text);
decimal Total = Price * Quantity;
TotalTextBox.Text = Total.ToString();
}
}
還有一些其他考慮,您的PriceTextBox_TextChanged方法重復了驗證方法的作業(通過重新決議數字)..因此驗證方法可以改為回傳小數或拋出例外 - 例外的內容將是要顯示的訊息在一個MessageBox。然后,您需要將驗證嘗試包裝在一個try {} catch{}塊中。您似乎也QuantityTextBox沒有任何驗證就使用了- 但也許這只是為了這個例子。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/409441.html
標籤:
上一篇:不在從Object派生的類中輸入Equals()方法
下一篇:根據日期范圍查找確切的周數
