Home > OS >  Convert method won't work when I'm trying to convert string variables to numeric & DateTim
Convert method won't work when I'm trying to convert string variables to numeric & DateTim

Time:09-07

So, I am using C#/.NET and am using Npgsql. Basically, I keep running into the error System.InvalidCastException: 'Can't write CLR type System.String with handler type NumericHandler' and I can't seem to resolve it.

The error seems pretty self-explanatory. Basically, I'm trying to use a string but Postgresql wants a Numeric data type. (Would that be a decimal or double data type?)

For some context, I am re-writing old VB code to C# and in the VB version the initial declarations of the numeric variables are strings. And in the code there is some string manipulation methods that are used.

My thought process was it'd be easier and faster to just let the string manipulation stuff happen and then convert it to a decimal or a double later on. (Decimal's and Double's are Numeric postgresql equivalents, I think?)

So here's an example of the initial declartions:

string tno = "";
string iw = "";
string ws = "";
string ftg = "0";
string hl = "0";
string ll = "0";
string date = "2012/02/04";
string va = "0";
string dev = "0";

Later on in the code there are some string manipulation methods that are used. As I said earlier I thought it'd be faster to just use some Conversion methods to convert the strings to their proper data types before feeding it to postgresql.

For example:

Convert.ToDecimal(tno);

Here's an example of the SQL string:

string sqlString = @"UPDATE header
SET ft = @gftg, high_limit=@ghl, low_limit=@gll, start_date = @gsdd, avg_ga = @gvgga, std_dev = @gstd
WHERE cmpy_id = 'ABC' and tag_no = @gto and ip_num = @gim";

Here's the Npgsql parameter code:

                                                    cmd.Parameters.Add("@gim", NpgsqlTypes.NpgsqlDbType.Varchar).Value = iw;
                                                    cmd.Parameters.Add("@gftg", NpgsqlTypes.NpgsqlDbType.Numeric).Value = ftg;
                                                    cmd.Parameters.Add("@ghl", NpgsqlTypes.NpgsqlDbType.Numeric).Value = hl;
                                                    cmd.Parameters.Add("@gll", NpgsqlTypes.NpgsqlDbType.Numeric).Value = ll;
                                                    cmd.Parameters.Add("@gsdd", NpgsqlTypes.NpgsqlDbType.Date).Value = date;
                                                    cmd.Parameters.Add("@gvgga", NpgsqlTypes.NpgsqlDbType.Numeric).Value = va;
                                                    cmd.Parameters.Add("@gstd", NpgsqlTypes.NpgsqlDbType.Numeric).Value = dev;

This isn't really working though and it's probably for an obvious reason that I'm hoping you guys can help me with.

  • Related