将字符串转换为十进制
我尝试将字符串转换为小数。但是在执行之后它会在更新时说intput string的格式不正确。
我在文本框中提供12567作为输入。我在后端添加了sqldbtype.decimal。
这里是conde snip:
hi i am try to convert string to a decimal. but after execution it say intput string not in correct format while updating.
i am providing 12567 as input in textbox. I have add it with sqldbtype.decimal at backend.
here is conde snip:
cmd.Parameters.Add("@Amount ",SqlDbType.Decimal).Value = Convert.ToDecimal (obentity.Amount);
此行给出错误。
用户可以自由输入字符串或小数值到文本框
感谢advnace
this line give error.
user is free to enter string or decimal value to textbox
thanks in advnace
首先,在尝试访问任何SQL之前转换它 - 如果用户输入了一个愚蠢的金额,你应该告诉他而不是继续。
First, convert it before you try to access any SQL - if the user has entered a silly amount, you should tell him instead of continuing.
string s = "1234.56";
double d;
if (double.TryParse(s, out d))
{
...
}
其次,你不应该使用Parameters.Add - 它已被折旧了很长时间,并被AddWithValue取代。
Second, you shouldn't use Parameters.Add - it has been depreciated for a long time, and superseded by AddWithValue.
double d;
if (double.TryParse(obentity.Amount, out d))
{
cmd.Parameters.AddWithValue("@Amount ", d);
...
}
这假定obentity.Amount是一个字符串,包含一个应该是一个双精度值。
This assumes that obentity.Amount is a string, containing a should-be-a-double value.
如果用户输入数值,则显示正确的结果。如果用户输入字符串值,如a,adasd,asdjfksl。然后它无法转换为十进制。
因此,您可以将一些(javascript / serverSide)验证放到文本框中,以便用户只输入数值(23,34.343,43322etc)。
一切顺利。
if the user enters the numeric value then its showing right result. If user enters the string values like- "a","adasd","asdjfksl". Then its not able to convert to decimal.
So better you put some (javascript/serverSide) validations to the textbox so that user may enter only numeric values(23,34.343,43322etc) .
All the Best.