Reputation: 4964
I'm using DataReader to read the rows from my sqlcommand.
my problem is that i want return all columns from my database and error is that he found DBNull in one column.
how can i do to solved this?
Note: the column which return Null is of type string.
while(sqlDataReader.Read())
{
if (sqlDataReader.HasRows)
{
mylist.Add(new User()
{
Id = (int)sqlDataReader["Id"],
Name = (string)sqlDataReader["Name"],
File= (string)sqlDataReader["File"] <-- This is the one which contains some columns Null
});
}
}
Upvotes: 1
Views: 1262
Reputation: 22619
Try:
File=(sqlDataReader["File"] as string).GetValueOrDefault("");
Refer to the documentation for GetValueOrDefault.
Upvotes: 4
Reputation: 2170
Use IsDBNull() method from DataReader.
if (sqlDataReader.HasRows)
{
while(sqlDataReader.Read())
{
if(!sqlDataReader.IsDBNull(1)) //pass the column index.
{
object value=sqlDataReader[1];
}
}
}
Upvotes: 4