I have added 4 new fields. A country, State, City, Age, Language to my table and these all have null values. if I comment these fields. I am able to show all data but with these fields, I am getting an error
Object cannot be cast from DBNull to other types
Code:
public List<UserModel> listall() {
List <UserModel> lst = new List <UserModel>();
int i = 0;
try {
using(con = new SqlConnection(connStr)) {
cmd = new SqlCommand("Usp_CrudOperation", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Action", "View");
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read()) {
i++;
lst.Add(new UserModel {
Id = Convert.ToInt32(rdr["Id"]),
Name = rdr["Name"].ToString(),
Gender = rdr["Gender"].ToString(),
Email = rdr["Email"].ToString(),
Password = rdr["Password"].ToString(),
DoB = Convert.ToDateTime(rdr["DoB"]),
Country = rdr["Country"].ToString(),
State = rdr["State"].ToString(),
City = rdr["City"].ToString(),
Age = Convert.ToInt32(rdr["Age"]),
Language = rdr["Language"].ToString(),
});
}
}
}
catch (SqlException se)
{
throw se;
}
finally
{
con.Close();
con.Dispose();
}
return lst;
}