1

I have a DataReader and a StringBuilder (C#.NET) used in the following way;

while (reader.Read())
{
    sb.AppendFormat("{0},{1},{2},",reader["Col1"], reader["Col2"], reader["Col3"]);
}

Which works great for my use, but when a row is null I need it to return "null", instead of just "". What would be a good way of accomplishing that?

Suggestions are very appreciated

4 Answers 4

4

Try:

Convert.IsDBNull(reader["Col1"]) ? "null" : reader["Col1"]

Alternatively, if you're going to be using this repeatedly, this is probably an ideal candidate for a tightly scoped Extension Method, for example:

public static class ExtensionMethods
{
    public static object GetValueOrNull(this SqlDataReader reader, string key)
    {
        return Convert.IsDBNull(reader[key]) ? (object)"null" : reader[key];
    }
}

So you could then write:

var valueOfReader = reader.GetValueOrNull("Col1");

Which would definately make things tidier if you needed to use this logic multiple times inside one StringBuilder.AppendFormat call:

while (reader.Read())
{
    sb.AppendFormat("{0},{1},{2},",reader.GetValueOrNull("Col1"), reader.GetValueOrNull("Col2"), reader.GetvalueOrNull("Col3"));
}
Sign up to request clarification or add additional context in comments.

5 Comments

Great answer! Thank you very much for taking the time to write up all of that.
Of course, if you did go down the extension method route, you could return anything (such as a value you pass in) if it's null, not just "null" - which would make it more flexible =)
The simple code works great, it seems however that "this SqlDataReader" doesn't work in a static context. And "the name 'reader' does not exist in the current context". Do you have a quick comment on how to fix those? I'm unfortunately fairly newbie here.
Ahh my bad - sorry, I missed something - I've edited the extension method accordingly :)
@Rob - Thanks for taking the time! I very much appreciate it. I managed to get your code working.
4
reader["Col1"] == DBNull.Value ? "null" : Convert.ToString(reader["Col1"])

1 Comment

I voted to delete my answer, which was the same. I was a few seconds too late!
1
reader.IsDBNull(indexOfColumn) ? "null" : reader[indexOfColumn].ToString();

Comments

1
(string)reader["Col1"] ?? "null"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.