I'm trying to use SqlDataReader to retrieve values from a row and pass them
to a business class constructor (used by ObjectDataSource) but get exception
if the string field contains a null value in the table. Is there some way to
have the DataReader return String.Empty if the column is null?
Any suggestions on how to handle this would be greatly appreciated.
public RegistrantDetails GetRegistrant(int registrantId){
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("GetRegistrant", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@RegistrantId", SqlDbType.Int, 4));
cmd.Parameters["@RegistrantId"].Value = registrantId;
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
// Get the first row.
reader.Read();
RegistrantDetails det = new RegistrantDetails(
(int)reader["RegistrantId"],
(string)reader["FirstName"],
(string)reader["MI"], // this column is null and generates exception
...
);
reader.Close();
return det;
....
Dabbler - 05 Apr 2006 08:03 GMT
sorry, posted to the wrong group. solved the problem by testing for DBNull
as in
reg.MI = (string)(reader["MI"] is DBNull ? String.Empty : reader["MI"]);
tedious, as I have 50+ columns.
> I'm trying to use SqlDataReader to retrieve values from a row and pass them
> to a business class constructor (used by ObjectDataSource) but get exception
[quoted text clipped - 26 lines]
> return det;
> ....