Solved

C# .NET MySql - handling null fields

Posted on 2008-06-14
2
1,601 Views
Last Modified: 2013-12-17
In my MySQL table I allow NULL values in some fields.
When I itterate through the result set I get an error whenever the reader hits such a NULL value.
Here is the code:
IDataReader reader = dbcmd.ExecuteReader();

                while (reader.Read())
                {

                    string[] catalog_info = {
                (string)reader["tab_name"], (string)reader["document_name"], (string)reader["comment_text"]};

                    dataGridViewCurrentSessionPatientDocuments.Rows.Add(catalog_info);

                }

Here is the error: "Unable to cast object of type 'System.DBNull' to type 'System.String'."
What I need is to instruct the reader to substitute an emplty string ("") for a NULL value


0
Comment
Question by:eugene-g
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 143

Accepted Solution

by:
Guy Hengel [angelIII / a3] earned 50 total points
ID: 21786744
or do it directly in the query? ...
COALESCE(yourfield, '' )

in the .net code:
string[] catalog_info = { 
                (string) (reader["tab_name"] == DBNull.Value ? "" : reader["tab_name"] )
              , (string) (reader["document_name"] == DBNull.Value ? "" : reader["document_name"] )
              , (string) (reader["comment_text"] == DBNull.Value ? "" : reader["comment_text"] )
               };

Open in new window

0
 

Author Closing Comment

by:eugene-g
ID: 31467258
Veru ellegant and convinient. Thanks
0

Featured Post

The Orion Papers

Are you interested in becoming an AWS Certified Solutions Architect?

Discover a new interactive way of training for the exam.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
Containers like Docker and Rocket are getting more popular every day. In my conversations with customers, they consistently ask what containers are and how they can use them in their environment. If you’re as curious as most people, read on. . .
THe viewer will learn how to use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.
The viewer will learn how to use and create new code templates in NetBeans IDE 8.0 for Windows.

729 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question