The input string was not in the correct format. Convert string to double

I am new to C #, an empty line for double conversion can be done in the button1_click event .. but doing this under Public Form1() , it gives me this error

The input line was not the correct format.

Here is the code .. (form1.cs and class Guy.cs)

  using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); guy1 = new Guy() ; guy1.guyname = textBox1.Text; guy1.guycash = double.Parse(textBox2.Text); } } Guy guy1 ; private void button1_Click(object sender, EventArgs e) { label5.Text = guy1.TakeCash(double.Parse(textBox3.Text)).ToString(); } } } 

Guy.cs Code:

 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { class Guy { private string name; private double cash; public string guyname { get { return name; } set { name = value; } } public double guycash { get { return cash ; } set { cash = value; } } public double TakeCash(double amount) { if (cash > amount) { cash -= amount; return cash; } else { MessageBox.Show("Not enough Cash."); return 0; } } } } 

the error is caused by the line guy1.guycash = double.Parse(textBox2.Text); when I try to execute double.TryParse(textbox2.Text, out x) in If () in front of it, it returns false.

How to solve it please? thanks in advance.

+4
source share
3 answers

Continuing the response from:

 double d; if(!Double.TryParse(textBox2.Text, out d)){ return; // or alert, or whatever. } guy1 = new Guy() ; guy1.guyname = textBox1.Text; guy1.guycash = d; 

What you are doing is trying to parse, and if that fails, follow some other steps. Since the user can enter whatever he wants, this ensures that if you cannot analyze the input (because it is not a decimal), you can handle it well and let them know to correct their input.

+4
source

That should be good

 double d; Double.TryParse(String.Empty, out d); 

Double.TryParse Method (String, Double%)

+2
source

It seems like the problem is that you are not processing user input inerper. You are trying to parse a string from a text field to double, not assuming that it cannot be parsed normally (for example, the user can enter "abcd" in the text field). Your code should use the TryParse method and display an error message when the input was not processed.

I think the parsing failed due to non-numeric input or due to cultural issues (for example, you have a "." As a desimal character by user numbers using ",").

+1
source

Source: https://habr.com/ru/post/1304040/


All Articles