How to use GetType() in C# to detect column type

bek
bek used Ask the Experts™
on
In C#, I need to identify the type of a column in a DataTable.  This is part of a large operation, but basically I am building an insert statement so that I can write a DataTable to a SQL Server database table.  However, I've found that GetType() doesn't return the type of the column, but rather the type of the data inside it.  This is a problem, because I need to know whether to insert a '0' or a blank, depending on whether the column is Int64 or String.  Below is my sample code that nearly works, but not quite.  The r[c].GetType().Name line is the problem.  Does anyone know how to check the type of the *column* instead of the type of data that's inside it?

foreach (DataRow r in dt.Rows) {
      foreach (DataColumn c in dt.Columns) {

            if (r[c].GetType().Name.Equals ("String")) {
                  if (r[c].ToString().Equals (""))
                        BuiltString = BuiltString + "' ',";
                  else
                        BuiltString = BuiltString + "'" + r[c] + "',";
            } else if (r[c].GetType ().Name.Equals ("Int64")) {
                  if (r[c].ToString().Equals (""))
                        BuiltString = BuiltString + "0,";
                  else
                        BuiltString = BuiltString + r[c].ToString() + ',';
            }
      }


In desperation, I added some code later to check for null values using an extra IF statement:

      } else if (r[c].GetType().Name.Equals ("DBNull"))
                     BuiltString = BuiltString + Convert.ToChar(0).ToString() + ",";

But this doesn't work, either.  If I could just check the column type, I would know the correct value to insert.  Does anyone know how to do this?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Commented:
hi, try it with .DataType instead

something like
              if (c.DataType.Name.Equals("String"))

Commented:
hm so, did it work? :)
bek

Author

Commented:
Sorry for the delay, Limbeck. :)   I had held off responding because I hadn't had a chance to test until this morning, but your solution is working just fine.  Wish I'd thought to check the column properties.

Thanks so much!

Commented:
no problem, sorry for being impatient.:)

Ed.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial