I have this data in SQLServer:
Title that is in float
I am making a query in c# mvc to load this data but the truth is that it is giving me a conversion error, does anyone know how to convert correctly?
Class:
public class ProvidusCuotas{
private float titulo { get; set; }
private string nombre { get; set; }
private string cuota { get; set; }
public ProvidusCuotas(float titulo, string nombre, string cuota) {
this.titulo = titulo;
this.nombre = nombre;
this.cuota = cuota;
}
public ProvidusCuotas() {}
}
Model:
public List<ProvidusCuotas> cargarDatos(){
List<ProvidusCuotas> salida = new List<ProvidusCuotas>();
SqlConnection conn = new SqlConnection("cadenadeConexion");
conn.Open();
SqlCommand comand = new SqlCommand("SELECT titulo, apellido +', '+nombre,max(Cuota) FROM V_CuetaWeb GROUP BY titulo, apellido, nombre ORDER BY titulo ASC", conn);
SqlDataReader dr = comand.ExecuteReader();
while (dr.Read()){
float titulo = Convert.ToSingle(dr.GetFloat(0));//aquí es donde sale el error de conversión
string nombre = dr.GetString(1);
string cuota = Convert.ToString(dr.GetDouble(2));
ProvidusCuotas p = new ProvidusCuotas(titulo,nombre, cuota);
salida.Add(p);
}
conn.Close();
return salida;
}
Mistake:System.InvalidCastException: 'La conversión especificada no es válida.'
Attached image of the view:
I advise changing the code to use the names of the fields instead of the indexes
by using the names you avoid problems that could be related to an incorrect reference
Something that if I notice you should evaluate is because a field
titulo
is numeric, while one that it representscuotas
is a string, I think you should do the opposite, the quotas are numericyou can always use the
tryparse()
I see 3 things in your problem:
The proper conversion for a float data type from SQL to C# is "Double", see this documentation: https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-data- type-mappings
When you pass the data from the DataReader for the title, you are converting to "Single", you should do "Convert.ToDouble(xxx)".
You should check if the data is = a DbNull.