问题
am trying to convert a decimal to a string which I have done sucesfully in the past but for some reason its deciding not to work now. I really can't get my head around it, I have set it to decimal in SQL Management Studio and used linq to entites to pass it through but for some bizarre reason unknown to mankind it thinks am asking for a datetime.
Code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
tblTest t = new tblTest();
t.tDecimal = Convert.ToDecimal(tbxDecimal.ToString());
t.Add(t);
}
catch (Exception ex)
{
System.Diagnostics.Debug.Write(ex.Message);
}
}
Can someone help me out here?
回答1:
First, you should always use System.Decimal.TryParse() instead of Convert.ToDecimal()
Second, assuming you're using some form of hungrian notation, and tbx means "textbox" in your notation, you're trying to convert a textbox, not the text IN the textbox.
instead of
tbxDecimal.ToString()
you need
tbxDecimal.Text.ToString()
Finally, have you put a breakpoint in to find out what the value you're trying to convert really is? It may be different than you're expecting.
回答2:
Perhaps it is because the string uses a dot instead of a coma, or the other way around.
回答3:
Perhaps tbxDecimal.ToString()== string.Empty
? Decimal.Parse will throw an exception if the string is empty
回答4:
To expand on Fredrik's answer: is there a CultureInfo/Localization mismatch?
回答5:
Why do you think it's datetime? Could you post the actual string?
Pay attention to decimal separator - '.' vs. ','
来源:https://stackoverflow.com/questions/4741385/input-string-was-not-in-a-correct-format-decimal-to-string