我的代码:
private void txtSubTotal_TextChanged(object sender, EventArgs e)
{
double subTotal = 0;
subTotal = Convert.ToDouble(txtPrice.Text) * Convert.ToDouble(txtQuantity.Text);
txtSubTotal.Text = "" + subTotal;
}
错误指出代码的这一部分可能有什么问题?
我的错误指向我的代码的这一部分可能是什么问题?
答案 0 :(得分:0)
如果txtPrice
或txtQuantity
中输入的文字不是数字Convert.ToDouble
,则会失败。所以你可以试试这样的方法:
double subTotal = 0;
double price, quantity;
if (double.TryParse(txtPrice.Text, out price) &&
double.TryParse(txtQuantity.Text, out quantity))
{
subTotal = price * quantity;
}
else
{
//Notify the exception
}
答案 1 :(得分:0)
您可以使用MaskedTextBox
控件确保用户可以在文本框中输入有效数据,方法是使用以下代码:
double price;
double qty;
if (Double.TryParse(txtPrice.Text, out price)&&
Double.TryParse(txtQuantity.Text, out qty)) // if done, both are valid numbers
{
double subTotal = 0;
subTotal = Convert.ToDouble(txtPrice.Text) * Convert.ToDouble(txtQuantity.Text);
txtSubTotal.Text = "" + subTotal.ToString();
}
else{
MessageBox.Show("Invalid Input");
}
答案 2 :(得分:0)
Import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let jobs = ["McDonalds", "Hardees", "Taco Bell"]
let schools = ["Univ of CO", "Univ of TX", "Univ of CA"]
override func viewDidLoad() {
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return jobs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "JobsCell", for: indexPath) as! Jobs
let job = jobs[indexPath.row]
cell.jobLbl.text = job
return cell
}
}
答案 3 :(得分:0)
如果您不确定输入,则应使用double.TryParse()方法。如果用户未传递预期值,则会抛出错误 Convert.ToDouble()方法。
但是,如果我们确定您将传递唯一的数字,那么您可以使用Convert.ToDouble()
Convert.ToDouble will throw an exception on non-numbers
Double.Parse will throw an exception on non-numbers or null
Double.TryParse will return false or 0 on any of the above without generating an exception.
试试这个
double price, quantity;
if(string.NullOrEmpty(txtPrice.Text)&&string.NullOrEmpty(txtQuantity.Text)
{
if (Double.TryParse(txtPrice.Text, out price)&&
Double.TryParse(txtQuantity.Text, out quantity))
{
double subTotal = 0;
subTotal = price * quantity;
txtSubTotal.Text = "" + subTotal.ToString();
}
}