4

这是代码:

autoInsert.Parameters.Add(new NpgsqlParameter("price", NpgsqlDbType.Numeric));
autoInsert.Parameters[0].Value = txt_price.Text;
        con.Open();
        autoInsert.ExecuteNonQuery();
        con.Close();

当我执行查询时,它显示错误:“输入字符串的格式不正确。” 如何将该字符串转换为数字。txt_price 是文本框。

4

2 回答 2

3
autoInsert.Parameters[0].Value = ConvertToInt32(txt_price.Text); 
于 2012-01-17T14:21:46.877 回答
2

顺便Numeric说一句,你已经向 Npgsql 保证你传递了一个数字。然后你传递了一个字符串。

如果您已经确定,由于其他代码,其中有一个十进制值txt_price并且不可能有其他任何东西,那么使用:

autoInsert.Parameters[0].Value = decimal.Parse(txt_price.Text);

否则,在执行任何其他操作之前,将其与代码结合以确保这一点:

decimal price;
if(!decimal.TryParse(txt_price.Text, out price))
{
   //code to display message that txt_price doesn't have a valid value.
   return;
}
using(var con = /*your code that constructs the connection*/)
{
  using(autoInsert = /*your code that returns to command*/)
  {
    autoInsert.Parameters.Add(new NpgsqlParameter("price", NpgsqlDbType.Numeric));
    autoInsert.Parameters[0].Value = price;
    con.Open();
    autoInsert.ExecuteNonQuery();
    con.Close();
  }
}
于 2012-01-17T14:39:09.190 回答