I have a simple Employee Database which allows me to add new a employee, with some of my textbox fields left empty (I'm using winform). It currently works ok in the database. It registers NULL values in place of the empty textboxes. My problem now is how to display all the employees from the database in a gridview: When I run the program, it pops up a messagebox saying "object cannot be cast from DBNull to other types". Is it because 'age' and 'married' columns in my database contain some null values? Please help, I'm trying to understand how to use nullable types in c# with mssql database.
public static List<Employee> GetEmployees()
{
List<Employee> empListToReturn = new List<Employee>();
SqlConnection conn = GetConnection();
string queryStatment = "SELECT * FROM Employee";
SqlCommand sqlCmd = new SqlCommand(queryStatment, conn);
try
{
conn.Open();
SqlDataReader reader = sqlCmd.ExecuteReader();
while (reader.Read())
{
Employee emp = new Employee();
emp.FirstName = reader["firstname"].ToString();
emp.LastName = reader["lastname"].ToString();
emp.Age = Convert.ToInt32(reader["age"]);
emp.Married = (reader["married"]);
empListToReturn.Add(emp);
}
reader.Close();
}
catch (SqlException ex)
{
throw ex;
}
finally
{
conn.Close();
}
return empListToReturn;
}