1

I am retriving sum of all tution fees from the database where it is equal to the entered admission number. Data type for the columns in the SQL SERVER is decimal(10,2). When i want to convert to double it is showing error "Specified cast is not valid". How to convert to double?

SqlConnection con6 = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
                    con6.Open();
                    string query = "SELECT sum(tutionfee) FROM fees where admno='"+admissionnumber.Text+"'";
                    SqlCommand comSelect = new SqlCommand(query, con6);
                    double ID = (double)comSelect.ExecuteScalar();

1 Answers1

2

You need to actually convert the value in C#. double and decimal are two different types in C#. The former is a built-in type and the latter is just a struct that is implemented mostly in C# itself. Since they aren't the same, you can't just cast them. The easiest way, in this case, is to use the Convert class:

Convert.ToDouble((decimal)comSelect.ExecuteScalar());
siride
  • 200,666
  • 4
  • 41
  • 62
  • 2
    He should be able to just do: `(double)(decimal)comSelect.ExecuteScalar();` This consists of an unboxing operation and a cast. He tried to combine them into one operation which is not legal. – Lasse V. Karlsen Jun 06 '15 at 15:54