hello I am using a reader to get a XML from a stored procedure.. now the stored procedure returns null if it does not find anything .. in the case I am testing.. it should not return anything but my code is failing.. it says there is a row.. but then when it gets to the reader.GetString(0); it says Data is Null. This method or property cannot be called on Null values.
How can I check for null int hat line XML = XML + reader.GetString(0);? it is passing the while(reader.Read() && reader.HasRows) check.. when I debug it says there is an item but then when it gets to the line mentioned above it throws the Data is null error. How can I fix this?
Here is my code
SqlDataReader reader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
string XML = "";
while (reader.Read() && reader.HasRows)
{
XML = XML + reader.GetString(0);
}
XML = "<ProductList>" + XML + "</ProductList>";
reader.开发者_如何学GoClose();
myConnection.Close();
return XML;
Use IsDBNull
first:
if (!reader.IsDBNull(0))
{
XML = XML + reader.GetString(0);
}
You can use IsDBNull method to check for null:
while (reader.Read())
{
if (!reader.IsDBNull(0))
{
XML = XML + reader.GetString(0)
}
}
UPDATE Removed the reader.HasRows call as it's redundant (as pointed out by someone else).
If I remember correct, the while (reader.Read() will make it go through the loop once even if there isn't data. Could be mistaken on that though. Couple things you can try are changing it to have a nested if like
while(reader.read())
{
if(reader.HasRows)
{
XML = XML + reader.GetString(0);
}
}
I would change the GetString(0) to GetValue(0).ToString(); May not make a difference but GetString and GetValue behave differently when nulls are involved.
精彩评论