Solved

C# .NET MySql - handling null fields

Posted on 2008-06-14
2
1,600 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

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

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

Creating and Managing Databases with phpMyAdmin in cPanel.
This article shows the steps required to install WordPress on Azure. Web Apps, Mobile Apps, API Apps, or Functions, in Azure all these run in an App Service plan. WordPress is no exception and requires an App Service Plan and Database to install
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
The viewer will learn how to use and create keystrokes in Netbeans IDE 8.0 for Windows.

697 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