Reputation: 453
My code is : I am retrieving the data fron database when i am doing the breakpoint it show the data in list,but it also give me a error
public static List<StudentScore> GetAllScore()
{
SqlConnection conn = MyDB.GetConnection();
string selectStm = "SELECT en.CourseID,en.Score,s.StudentID FROM EnrollmentTable en,Student s WHERE en.StudentID = s.StudentID";
SqlCommand command = new SqlCommand(selectStm, conn);
List<StudentScore> aStudentScore = new List<StudentScore>();
try
{
conn.Open();
SqlDataReader reader = command.ExecuteReader();
Console.WriteLine(reader.HasRows.ToString());
while (reader.Read())
{
StudentTable st = new StudentTable();
CourseTable cr = new CourseTable();
Enrollment enr = new Enrollment();
StudentScore score = new StudentScore();
enr.CourseData = cr;
enr.StudentData = st;
//score.EnrollmentData.StudentData.StudentID = reader["StudentID"].ToString();
//score.EnrollmentData.CourseData.CourseID = reader["CourseID"].ToString();
st.StudentID = reader["StudentID"].ToString();
cr.CourseID = reader["CourseID"].ToString();
score.Score = Convert.ToInt32(reader["Score"]);
score.EnrollmentData = enr;
aStudentScore.Add(score);
}
reader.Close();
return aStudentScore;
}
catch (SqlException ex)
{
throw ex;
}
finally
{
conn.Close();
}
}
}
}
It takes a data from database but show mw a this error.....Object cannot be cast from DBNull to other types so what it mean please tell me how to fix it?
Upvotes: 0
Views: 9870
Reputation: 477
This error is due to a null value in the database table, while retrieving data check null:
poco.LastUpdated = reader["Last_Updated"] == DBNull.Value ? null:Convert.ToDateTime(reader["Last_Updated"]);
Upvotes: 0
Reputation: 18843
you need to check if the reader is of type DBNULL
Call IsDBNull() on the reader to check the column before attempting to convert it:
using (reader = server.ExecuteReader(CommandType.Text, TopIDQuery, paramet))
{
while (reader.Read())
{
var column = reader.GetOrdinal("TopID");
if (!reader.IsDBNull(column))
topID = Convert.ToInt32(reader[column]);
}
}
}
Or, compare against DBNull.Value:
var value = reader["TopID"];
if (value != DBNull.Value)
{
topID = Convert.ToInt32(value);
}
Upvotes: 3
Reputation: 21
DBNull is used to represent a null value in a DataBase.
You should check if the value isn't DBNull before casting ir.
object score = reader["Score"];
score.Score = score == DBNull.Value ? 0 : Convert.ToInt32(score);
Upvotes: 2
Reputation: 3269
It means you have a NULL
value in the database. You have to check for it in the code, or change your column schemas to NOT NULL
.
st.StudentID = reader["StudentID"] == DBNull.Value ? null : reader["StudentID"].ToString();
cr.CourseID = reader["CourseID"] == DBNull.Value ? null : reader["CourseID"].ToString();
score.Score = reader["Score"] == DBNull.Value ? 0 : Convert.ToInt32(reader["Score"]);
You have to deal with the null
values in the C# objects now.
Upvotes: 5