开发者

How do I check a datareader for null?

开发者 https://www.devze.com 2023-02-10 07:40 出处:网络
I have an aspx page which allows a user to submit modified entries into the database, but when the user clicks Submit to fire the stored procedure I want to first run a check to see if a modified row

I have an aspx page which allows a user to submit modified entries into the database, but when the user clicks Submit to fire the stored procedure I want to first run a check to see if a modified row with the same relationship exists.

I am passing the results of the following query:

SELECT SwitchRoom.ModifiedID FROM SwitchRoom WHERE 
    SwitchRoomID = @ChkSwitc开发者_StackOverflowhRmID", constring; 

into a DataReader to determine if that relationship exists.

I need it to determine whether the reader returns NULL to allow the procedure to execute, if it doesn't, then don't allow the user to save the information.

I've tried the following:

if (dbreader = NULL)
{
 Fire Procedure
}
else
{
 "Error Message"
}

and I've even tried passing the reader into a datatable and running it against that without any luck.

How do I check the restults of a DataReader for null?


I prefer using ExecuteScalar with a query that counts the matching rows:

"SELECT count(*) FROM SwitchRoom WHERE SwitchRoomID = @ChkSwitchRmID"

Then compare the result of Execute scalar to zero. No null check required.

If you really want to use the reader method you can use the following property to check if it has any rows. The object will not be null even if it returns nothing.

if (dbReader.HasRows) {....}


Try if (!dbReader.Read() || dbreader.IsDbNull(field)} { .. }


The Reader will not return a null object, To find out if the reader returned any rows you can use if(dbreader.Read())


You're looking for the DBNull type. Databases don't send actual null-references, they send a special datatype in C# to represent a database NULL value.


So basically, you want to know if

SELECT SwitchRoom.ModifiedID
FROM SwitchRoom
WHERE SwitchRoomID = @ChkSwitchRmID

returns any records?

The reader would never, ever be null. You instead need to check that the reader contains no records to read.

if  (!dbReader.Read())
{
    // execute procedure
}
else
{
    // error
}
0

精彩评论

暂无评论...
验证码 换一张
取 消