简体   繁体   中英

Input string was not in a correct format (Decimal to String)

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?

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.

可能是因为字符串使用点而不是逗号来代替,或者相反。

Perhaps tbxDecimal.ToString()== string.Empty ? Decimal.Parse will throw an exception if the string is empty

扩展Fredrik的答案:是否存在CultureInfo / Localization不匹配?

Why do you think it's datetime? Could you post the actual string?

Pay attention to decimal separator - '.' vs. ','

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM