James Teare
James Teare

Reputation: 372

Reading "real" data type in a SQL Server database in C#

I have a method that pulls down data from a SQL Server Compact db:

// Open the same connection with the same connection string.
using (SqlCeConnection con = new SqlCeConnection(DatabaseControl.conString))
{
   con.Open();
   // Read specific values in the table.
   using (SqlCeCommand com = new SqlCeCommand("SELECT Result FROM CpuResults WHERE Date = @date", con))
   {
      List<float> results = new List<float>();
      com.Parameters.AddWithValue("date", Form1.date);
      SqlCeDataReader reader = com.ExecuteReader();

      while (reader.Read())
      {
         float resultsoutput = reader.GetInt32(0);
         results.Add(resultsoutput);
      }

The "type" for results in the "Result" column on cpuResults is defined as Real. I am trying to get this data into a float format as the data within the Result column is e.g. 0.02 and 1.23 etc. Although when I run my method I get:

Specified cast is not valid.

If I change the data type of column Result to int, the problem does not happen..

Upvotes: 1

Views: 4296

Answers (3)

user758977
user758977

Reputation: 441

Why don't you try reader.GetFloat(0)?

Upvotes: 0

Arnold Zokas
Arnold Zokas

Reputation: 8560

Is this where your cast is failing?

float resultsoutput = reader.GetInt32(0);

Try this:

float resultsoutput = reader.GetFloat(0);

Upvotes: 0

Oded
Oded

Reputation: 498942

This line:

float resultsoutput = reader.GetInt32(0);

You are trying to get an integer and place the value into a float.

Either get a float to begin with:

float resultsoutput = reader.GetFloat(0);

Or change the type of variable:

int resultsoutput = reader.GetInt32(0);

Upvotes: 5

Related Questions