Search code examples
c#sqlvisual-studio-2010npgsql

npgsql string to numeric


This is the code:

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

When I execute the query it shows the error: "Input string was not in a correct format." How do I convert that string to Numeric. txt_price is textbox.


Solution

  • In passing Numeric you've assured Npgsql that you were passing a number. Then you passed a string.

    If you're already sure, due to other code, that there's a decimal value in txt_price and there couldn't possibly be anything else, then use:

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

    Otherwise, combine it with the code to ensure this, before you do anything else:

    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();
      }
    }