ObjectDataSource with nulls returned from DataReader

D

Dabbler

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;
.....
 
D

Dabbler

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top