Reputation: 109
Hello there I'm having a problem I can't find a solution, in my laptop everything works fine, but on server it gives me this error: "
Error message:
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 Blue.Adesao.GetAdesoes(SqlConnection conexao, SqlTransaction trans) at listagem_form_obras.GetAdesoes()"
The function about:
public static DataTable GetAdesoes ( SqlConnection conexao, SqlTransaction trans ) {
SqlCommand comando;
String sql;
sql = "SELECT id, data_criacao, nome, nif, telefone, email, valido " +
"FROM forms_adesao_entidade ";
comando = new SqlCommand(sql, conexao, trans);
SqlDataAdapter dtadapter = new SqlDataAdapter(comando);
DataTable dt = new DataTable();
dtadapter.Fill(dt);
dt.Columns.Add("dataFormatada", System.Type.GetType("System.String"));
dt.Columns.Add(new DataColumn("validacao", System.Type.GetType("System.String")));
foreach(DataRow r in dt.Rows) {
int valido = (int)r.Field<int>("valido");
r["validacao"] = Adesao.GetValidacao(valido, conexao);
r["dataFormatada"] = Utilidades.FormatarData(r.Field<DateTime>("data_criacao"));
}
return dt;
}
public static string GetValidacao ( int IDValido, SqlConnection conexao ) {
string sql = "";
DataTable dt = new DataTable();
sql = "SELECT [designacao] FROM [forms_estados] WHERE id=@IDValido";
SqlCommand comando = new SqlCommand(sql, conexao);
comando.Parameters.Add(new SqlParameter("@IDValido", SqlDbType.Int));
comando.Parameters["@IDValido"].Value = IDValido;
SqlDataAdapter dtadapter = new SqlDataAdapter(comando);
dtadapter.Fill(dt);
return dt.Rows[0].Field<string>("designacao");
}
Database
in front-end I have a simple gridview.
Upvotes: 2
Views: 520
Reputation: 6030
The line int valido = (int)r.Field<int>("valido");
is causing the error, right?
Your database allows this field to be nullable. So this may be the problem. When you encounter a record with a null-valido, the cast isn't possible.
You could try something like the following:
foreach(DataRow r in dt.Rows)
{
int valido = r.IsNull("valido") ? 0 : r.Field<int>("valido");
r["validacao"] = Adesao.GetValidacao(valido, conexao);
r["dataFormatada"] = Utilidades.FormatarData(r.Field<DateTime>("data_criacao"));
}
Upvotes: 4
Reputation: 941455
A decent disassembler is a good way to find out why the code failed. Mine says:
private static T ValueField(object value)
{
if (DBNull.Value == value)
{
throw DataSetUtil.InvalidCast(Strings.DataSetLinq_NonNullableCast(typeof(T).ToString()));
}
return (T) value;
}
That leaves only one possibility, the column in the table you query contains a null. Your screenshot of the table design does not exclude that possibility, you allow "valido" to be null. The exception message should have told you this, be sure you can see it.
Upvotes: 2