1

When I Execute the following code, I get an error saying.

System.InvalidCastException: Specified cast is not valid.
   at System.Data.DataRowExtensions.UnboxT`1.ValueField(Object value)
   at System.Data.DataRowExtensions.Field[T](DataRow row, String columnName)
   at ProbabilityFunctions.Program.Main(String[] args) in C:\Users\....:line 38Press any key to continue . . .

What I am trying to do in this code is, I am retrieving data from a table and storing it into another table. I am passing this table as an argument into a classifier to undergo further operation. Please tell me the error. Datatypes of height,uname are varchar... others are int...

using System;
    using System.Data;
    using MySql.Data.MySqlClient;

    namespace ProbabilityFunctions
    {
        public class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    String con = "SERVER=localhost;DATABASE=sample;UID=root;password=password";
                    MySqlConnection conn = new MySqlConnection(con);
                    String s = "select * from cart";
                    MySqlCommand cmd = conn.CreateCommand();
                    MySqlCommand cmd2 = conn.CreateCommand();
                    cmd2.CommandText = "select count(*) from cart";
                    conn.Open();
                    int z = Convert.ToInt32(cmd2.ExecuteScalar());

                    conn.Close();
                    MySqlDataAdapter dat = new MySqlDataAdapter(s, conn);
                    DataTable tbl = new DataTable();

                    dat.Fill(tbl);
                    cmd.CommandText = s;
                    DataTable table = new DataTable();
                    table.Columns.Add("name");
                    table.Columns.Add("Height", typeof(double));
                    table.Columns.Add("cost", typeof(double));
                    table.Columns.Add("FootSize", typeof(double));


                    for (int i = 0; i < z; i++)
                    {
                        DataRow row = tbl.Rows[i];
                        Double height = row.Field<Double>("height");
                        Double fsize = row.Field<Double>("fsize");
                        Double cost = row.Field<Double>("cost");
                        String uname = row.Field<String>("uname");
                        table.Rows.Add(uname, height, cost, fsize);
                    }


                    Classifier classifier = new Classifier();
                    classifier.TrainClassifier(table);

                    Console.WriteLine(classifier.Classify(new double[] { 4, 150, 12 }));
                    Console.Read();
                }
                catch (Exception ex)
                {
                    Console.Write(ex.ToString());
                }
                }
        }
    }
9
  • 6
    What line do you get the error? Commented Nov 11, 2013 at 17:57
  • Please tell us the error. What line is throwing the exception? Commented Nov 11, 2013 at 17:57
  • Don't call conn.Close(); before code that uses conn. That's definitely going to cause problems. Commented Nov 11, 2013 at 17:59
  • 2
    @lauCosma Convert.ToInt32 only throws a FormatException or OverflowException, not an InvalidCastException. Check here Commented Nov 11, 2013 at 18:01
  • 1
    If Height is a varchar, it can't directly be cast as a double; you'll need to assign it to a string and use double.Parse() or double.TryParse() Commented Nov 11, 2013 at 18:10

2 Answers 2

4

This is likely happening on one of these lines:

Double height = row.Field<Double>("height");
Double fsize = row.Field<Double>("fsize");
Double cost = row.Field<Double>("cost");

You will receive this exception if the underlying field type can not be cast to a double directly. From the documentation for Field<T>, InvalidCastException is thrown when:

The value type of the underlying column could not be cast to the type specified by the generic parameter, T.

Given the stack trace, it appears your "height" column within the underlying table is not actually numeric, and can't be cast to a double. If it's stored as a string in the input dataset, for example, you'll have to extract a string and convert to a double afterwards.

Sign up to request clarification or add additional context in comments.

Comments

1

Now it is clear. You cannot unbox a boxed int to double or any other type. Only possible types allowed are int and Nullable<int>.

Get Field as int and convert it to double then, It should work

double height = (double)row.Field<int>("height");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.