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 request, it shows an error: "The input string was not in the correct format." How to convert this string to numeric. txt_price is a text field.

+4
source share
2 answers

Passing Numeric , you assured Npgsql that you were passing the number. Then you passed the string.

If you are already sure, due to other code, that there is a decimal value in txt_price and there could be nothing else, use:

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

Otherwise, combine it with the code to verify this before doing 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(); } } 
+2
source
 autoInsert.Parameters[0].Value = ConvertToInt32(txt_price.Text); 
+3
source

Source: https://habr.com/ru/post/1391459/


All Articles