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());
}
}
}
}
conn.Close();before code that usesconn. That's definitely going to cause problems.Convert.ToInt32only throws aFormatExceptionorOverflowException, not anInvalidCastException. Check herevarchar, it can't directly be cast as adouble; you'll need to assign it to astringand usedouble.Parse()ordouble.TryParse()