Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Convert Null db field to string

Convert Null db field to string

Scheduled Pinned Locked Moved C#
databasesecurityhelpquestion
10 Posts 4 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • K Offline
    K Offline
    kallileo
    wrote on last edited by
    #1

    I use this code to read some records from a access database with contacts exported from Outlook. I get an error when the content of a field in the db is NULL bc it cannot be converted to string. How could I correct this and the convert a Null field in a " " string? Thanks static void Main() { Program instan = new Program(); instan.ReadContacts(); Console.Read(); } public void ReadContacts() { try { OleDbDataReader reader = null; OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\\AGH\\epafes_outlook_2007.accdb;Persist Security Info=False"); string comStr = "SELECT FirstName, LastName, BusinessPhone FROM Contacts"; OleDbCommand cmd = new OleDbCommand(comStr, conn); conn.Open(); reader = cmd.ExecuteReader(); int i=1; while (reader.Read()) { string FName = (string)reader["FirstName"]; string LName = (string)reader["LastName"]; string BPhone = (string)reader["BusinessPhone"]; Console.Write("{0,-4}", i); Console.Write("{0,-13}", FName); Console.Write("{0,-13}", LName); Console.Write("{0}", BPhone); Console.WriteLine(); i++; } Console.WriteLine("\nFinish"); conn.Close(); reader.Close(); } catch (Exception e) { Console.Write(e); } }

    C L K 3 Replies Last reply
    0
    • K kallileo

      I use this code to read some records from a access database with contacts exported from Outlook. I get an error when the content of a field in the db is NULL bc it cannot be converted to string. How could I correct this and the convert a Null field in a " " string? Thanks static void Main() { Program instan = new Program(); instan.ReadContacts(); Console.Read(); } public void ReadContacts() { try { OleDbDataReader reader = null; OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\\AGH\\epafes_outlook_2007.accdb;Persist Security Info=False"); string comStr = "SELECT FirstName, LastName, BusinessPhone FROM Contacts"; OleDbCommand cmd = new OleDbCommand(comStr, conn); conn.Open(); reader = cmd.ExecuteReader(); int i=1; while (reader.Read()) { string FName = (string)reader["FirstName"]; string LName = (string)reader["LastName"]; string BPhone = (string)reader["BusinessPhone"]; Console.Write("{0,-4}", i); Console.Write("{0,-13}", FName); Console.Write("{0,-13}", LName); Console.Write("{0}", BPhone); Console.WriteLine(); i++; } Console.WriteLine("\nFinish"); conn.Close(); reader.Close(); } catch (Exception e) { Console.Write(e); } }

      C Offline
      C Offline
      Colin Angus Mackay
      wrote on last edited by
      #2

      string FName = string.Empty;
      object temp = reader["FirstName"];
      if (temp != DBNull.Value)
      FName = (string)temp;


      Upcoming events: * Glasgow: Mock Objects, SQL Server CLR Integration, Reporting Services, db4o, Dependency Injection with Spring ... "I wouldn't say boo to a goose. I'm not a coward, I just realise that it would be largely pointless." My website

      1 Reply Last reply
      0
      • K kallileo

        I use this code to read some records from a access database with contacts exported from Outlook. I get an error when the content of a field in the db is NULL bc it cannot be converted to string. How could I correct this and the convert a Null field in a " " string? Thanks static void Main() { Program instan = new Program(); instan.ReadContacts(); Console.Read(); } public void ReadContacts() { try { OleDbDataReader reader = null; OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\\AGH\\epafes_outlook_2007.accdb;Persist Security Info=False"); string comStr = "SELECT FirstName, LastName, BusinessPhone FROM Contacts"; OleDbCommand cmd = new OleDbCommand(comStr, conn); conn.Open(); reader = cmd.ExecuteReader(); int i=1; while (reader.Read()) { string FName = (string)reader["FirstName"]; string LName = (string)reader["LastName"]; string BPhone = (string)reader["BusinessPhone"]; Console.Write("{0,-4}", i); Console.Write("{0,-13}", FName); Console.Write("{0,-13}", LName); Console.Write("{0}", BPhone); Console.WriteLine(); i++; } Console.WriteLine("\nFinish"); conn.Close(); reader.Close(); } catch (Exception e) { Console.Write(e); } }

        L Offline
        L Offline
        Le centriste
        wrote on last edited by
        #3

        kallileo wrote:

        string FName = (string)reader["FirstName"]; string LName = (string)reader["LastName"]; string BPhone = (string)reader["BusinessPhone"];

        If a column is nullable in the DB, you should check for nullity in your code. Unfortunately, it is not the same as .NET null. You have to do it this way:

        if (reader.IsDBNull(reader.GetOrdinal("FirstName"))
        {
             FName = null; // Or String.Empty, as you see fit.
        }
        else
        {
             FName = (string)reader["LastName"];
        }
        

        ` ----- _If atheism is a religion, then not collecting stamps is a hobby._ -- Unknown `

        C 1 Reply Last reply
        0
        • L Le centriste

          kallileo wrote:

          string FName = (string)reader["FirstName"]; string LName = (string)reader["LastName"]; string BPhone = (string)reader["BusinessPhone"];

          If a column is nullable in the DB, you should check for nullity in your code. Unfortunately, it is not the same as .NET null. You have to do it this way:

          if (reader.IsDBNull(reader.GetOrdinal("FirstName"))
          {
               FName = null; // Or String.Empty, as you see fit.
          }
          else
          {
               FName = (string)reader["LastName"];
          }
          

          ` ----- _If atheism is a religion, then not collecting stamps is a hobby._ -- Unknown `

          C Offline
          C Offline
          Colin Angus Mackay
          wrote on last edited by
          #4

          Le Centriste wrote:

          You have to

          "have to" is a bit strong. You don't "have to" do it that way (although it is a reasonable way to check) as there are other reasonable alternatives.


          Upcoming events: * Glasgow: Mock Objects, SQL Server CLR Integration, Reporting Services, db4o, Dependency Injection with Spring ... "I wouldn't say boo to a goose. I'm not a coward, I just realise that it would be largely pointless." My website

          L 1 Reply Last reply
          0
          • C Colin Angus Mackay

            Le Centriste wrote:

            You have to

            "have to" is a bit strong. You don't "have to" do it that way (although it is a reasonable way to check) as there are other reasonable alternatives.


            Upcoming events: * Glasgow: Mock Objects, SQL Server CLR Integration, Reporting Services, db4o, Dependency Injection with Spring ... "I wouldn't say boo to a goose. I'm not a coward, I just realise that it would be largely pointless." My website

            L Offline
            L Offline
            Le centriste
            wrote on last edited by
            #5

            Yes, you're right. Wrong choice of words. I should have said "Here is an example".

            ----- If atheism is a religion, then not collecting stamps is a hobby. -- Unknown

            1 Reply Last reply
            0
            • K kallileo

              I use this code to read some records from a access database with contacts exported from Outlook. I get an error when the content of a field in the db is NULL bc it cannot be converted to string. How could I correct this and the convert a Null field in a " " string? Thanks static void Main() { Program instan = new Program(); instan.ReadContacts(); Console.Read(); } public void ReadContacts() { try { OleDbDataReader reader = null; OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\\AGH\\epafes_outlook_2007.accdb;Persist Security Info=False"); string comStr = "SELECT FirstName, LastName, BusinessPhone FROM Contacts"; OleDbCommand cmd = new OleDbCommand(comStr, conn); conn.Open(); reader = cmd.ExecuteReader(); int i=1; while (reader.Read()) { string FName = (string)reader["FirstName"]; string LName = (string)reader["LastName"]; string BPhone = (string)reader["BusinessPhone"]; Console.Write("{0,-4}", i); Console.Write("{0,-13}", FName); Console.Write("{0,-13}", LName); Console.Write("{0}", BPhone); Console.WriteLine(); i++; } Console.WriteLine("\nFinish"); conn.Close(); reader.Close(); } catch (Exception e) { Console.Write(e); } }

              K Offline
              K Offline
              kallileo
              wrote on last edited by
              #6

              I think I found it....and it seems to work. But I'm not realy sure if this is the right way to do it. string FName = Convert.ToString(reader["FirstName"]); string LName = Convert.ToString(reader["LastName"]); string BPhone = Convert.ToString(reader["BusinessPhone"]); Thanks -- modified at 9:17 Friday 20th July, 2007 This also works: string BPhone = reader["BusinessPhone"].ToString();

              C L 2 Replies Last reply
              0
              • K kallileo

                I think I found it....and it seems to work. But I'm not realy sure if this is the right way to do it. string FName = Convert.ToString(reader["FirstName"]); string LName = Convert.ToString(reader["LastName"]); string BPhone = Convert.ToString(reader["BusinessPhone"]); Thanks -- modified at 9:17 Friday 20th July, 2007 This also works: string BPhone = reader["BusinessPhone"].ToString();

                C Offline
                C Offline
                Colin Angus Mackay
                wrote on last edited by
                #7

                Curiously, if you look at what Convert.ToString actually does, it just boils down to the same as:

                string FName = reader["FirstName"].ToString();

                So, is DBNull.Value.ToString() the value that you really want back?


                Upcoming events: * Glasgow: Mock Objects, SQL Server CLR Integration, Reporting Services, db4o, Dependency Injection with Spring ... "I wouldn't say boo to a goose. I'm not a coward, I just realise that it would be largely pointless." My website

                L 1 Reply Last reply
                0
                • K kallileo

                  I think I found it....and it seems to work. But I'm not realy sure if this is the right way to do it. string FName = Convert.ToString(reader["FirstName"]); string LName = Convert.ToString(reader["LastName"]); string BPhone = Convert.ToString(reader["BusinessPhone"]); Thanks -- modified at 9:17 Friday 20th July, 2007 This also works: string BPhone = reader["BusinessPhone"].ToString();

                  L Offline
                  L Offline
                  Lost User
                  wrote on last edited by
                  #8

                  Hi Since string is a reference type you could also do it like this: string FName = reader["FirstName"] as string; string LName = reader["LastName"] as string; string BPhone = reader["BusinessPhone"] as string; greets M@u

                  K 1 Reply Last reply
                  0
                  • L Lost User

                    Hi Since string is a reference type you could also do it like this: string FName = reader["FirstName"] as string; string LName = reader["LastName"] as string; string BPhone = reader["BusinessPhone"] as string; greets M@u

                    K Offline
                    K Offline
                    kallileo
                    wrote on last edited by
                    #9

                    m@u wrote:

                    Hi Since string is a reference type you could also do it like this: string FName = reader["FirstName"] as string; string LName = reader["LastName"] as string; string BPhone = reader["BusinessPhone"] as string; greets M@u

                    Thanks....

                    Colin Angus Mackay wrote:

                    Curiously, if you look at what Convert.ToString actually does, it just boils down to the same as: string FName = reader["FirstName"].ToString(); So, is DBNull.Value.ToString() the value that you really want back?

                    Yes, it is ok to me...

                    1 Reply Last reply
                    0
                    • C Colin Angus Mackay

                      Curiously, if you look at what Convert.ToString actually does, it just boils down to the same as:

                      string FName = reader["FirstName"].ToString();

                      So, is DBNull.Value.ToString() the value that you really want back?


                      Upcoming events: * Glasgow: Mock Objects, SQL Server CLR Integration, Reporting Services, db4o, Dependency Injection with Spring ... "I wouldn't say boo to a goose. I'm not a coward, I just realise that it would be largely pointless." My website

                      L Offline
                      L Offline
                      Le centriste
                      wrote on last edited by
                      #10

                      DBNull.Value.ToString() returns an empty string, so it boils down to be the same as the examples we give, I believe.

                      ----- If atheism is a religion, then not collecting stamps is a hobby. -- Unknown

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups