I have added data from the database to the textbox but can't add a null value. I'd like to enter certain text if the field (not sure if thats what it's called) in the database is null.

if( (reader["Grey3"].ToString()) == DBNull.Value)

I've search online and read through a number of discussions but couldn't understand them too well.

Recommended Answers

All 5 Replies

Try it this way:

while (reader.Read())
 {
     textBox1.Text = reader["Grey3"] != (object)DBNull.Value ? (string)reader["Grey3"] : String.Empty;
 }

It didn't work, got the error "Invalid attempt to read when no data is present."

I modified the statement a tad also.

reader.Read();
textBox1.Text = reader["Grey3"] != (object)DBNull.Value ? (string)reader["Grey3"] : String.Empty;

Would that change the results of what you wrote?

Tried using your way and it doesn't work as expected. If the column isn't null then I'll get a debugging error. If it is null then I am unable to change the text of the text box after substituting

String.Empty;

with "applejacks" . I would like the text box to have text in it even if the column is null.

I was wrong, it worked as you wrote it. I was testing for a database entry that wasn't there because I had recreated my database and forgot to add it. Thanks alot.

your are welcome.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.