4

Hy, I'm getting this error on line _obj.Add(new data()... here is my code

SqlCommand com = new SqlCommand("sp_get_a", con)
        {
            CommandType = CommandType.StoredProcedure
        };
        _obj = new List<n>();
        con.Open();
        SqlDataReader rdr = com.ExecuteReader();
        if (rdr.HasRows)
        {
            while (rdr.Read())
            {
                _obj.Add(new data() { Id = rdr.GetInt32(0), na = rdr.GetString(1), Al = rdr.GetString(2), Sc = rdr.GetFloat(3), So = rdr.GetInt32(4), Ta = rdr.GetInt32(5), Ai = rdr.GetInt32(6), Sh = rdr.GetInt32(7) });
            }
        }
        else
        {
            throw new Exception("rdr don't have any rows");
        }
        con.Close();

my stored procedure

CREATE PROCEDURE sp_get_a

AS SELECT Id, Na, Al, Sc, So, Ta, Ai, Sh FROM x I don't have any double value and closest to double is Sc(float). so I tried Sc = Convert.ToSingle(rdr.GetFloat(3)). Where am I doing wrong ? Edit- My model

public class n
{
    public int Id { get; set; }
    public string Na { get; set; }
    public string Al { get; set; }
    public float Sc { get; set; }
    public int So { get; set; }
    public int Ta { get; set; }
    public int Ai { get; set; }
    public int Sh { get; set; }
}
Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
Shanks Limbu
  • 117
  • 1
  • 12
  • what is `new List();? – Vivek Nuna Jun 12 '20 at 03:40
  • what is datatype in database for this column?? – Vivek Nuna Jun 12 '20 at 03:45
  • 3
    You are receiving a 64 bit double and you cannot convert the number to a 32 bit float. because the range of a 32 bit double is not large enough to convert the number. You need to change the type of Sc from a float to a double. – jdweng Jun 12 '20 at 03:48
  • Hy Vivek, List is my model class. and datatype in database is same as shown in my public class n. Hy jdweng, Thank you. It solved my problem. I'd liketo know why I'm receiving 64 bit double(I'm assuming coming from database) even though it is stored as float. Also I'd like to ask why is it trying to convert to single by itself ? – Shanks Limbu Jun 12 '20 at 03:57

1 Answers1

13

You need to change the datatype of Sc from float to double

SQL Server real is equivalent to C# Single and SQL server float is equivalent to C# Double.

And you should consider @jdweng point also

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
  • 1
    Hy Vivek, Thank you for your equivalent explanation. This also clears why was it trying to convert itself even though I didn't tried to convert anything. @Jdwend point was helpful as well. – Shanks Limbu Jun 12 '20 at 04:08