1
   if (_dt.Rows.Count > 0)
            {
                foreach (DataRow row in _dt.Rows)
                {
                    pUsername = row["tUsername"] == DBNull.Value ? " " : row["tUsername"].ToString();
                    pDomain = row["tDomain"] == DBNull.Value ? " " : row["tDomain"].ToString();
                    pStatus = row["tStatus"] == DBNull.Value ? 0 : Convert.ToInt32(row["tStatus"].ToString());
                    // pAdmin = (bool)row["tInstallType"];
                }
            }

How can i read different types from datatable ?Do i have to go each time to string ? . Why can't i read as type integer from database ? I think the main problem is row["tStatus"].ToString()

t3choo
  • 81
  • 2
  • 9
  • Oh, and **thank you** for questioning that `Convert.ToInt32(row["myInt"].ToString())` madness. Too many novice developers just copy that style from bad Internet tutorials and books without realizing that it is just plain *wrong*. – Heinzi Jan 17 '16 at 18:00

3 Answers3

2

You can read integers directly from the data table:

int myInt = row.Field<int>("myInt");

int? myNullableInt = row.Field<int?>("myNullableInt");  // NULL (DB) -> null (C#)

int myInt = row.Field<int?>("myNullableInt") ?? 0;      // NULL (DB) -> 0 (C#)

This uses the new DataRowExtensions.Field method introduced with .net 3.5. Obviously, this is not restricted to ints but works for all primitive C# types and their nullable counterparts. Note that, contrary to the indexer, Field returns null for database NULL values rather than DBNull.Value.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • 1
    That compared with this is win "http://stackoverflow.com/questions/425389/c-sharp-equivalent-of-sql-server-datatypes" – t3choo Jan 17 '16 at 17:06
0

There is a generic extension method DataRow.Field, so in your example for pUsername you could do:

string pUsername = row.Field<string>( "tUsername" );

and

int? pStatus = row.Field<int?>("tStatus")

Which are imo, much cleaner as well.

Brandon Moretz
  • 7,512
  • 3
  • 33
  • 43
0

There is Field language extension methods for DataRow.

Example

foreach (DataRow row in dt.Rows)
{
    Console.WriteLine("{0} - {1}",row.Field<string>("FirstName"), row.Field<int?>("SomeIntField"));
}
Karen Payne
  • 4,341
  • 2
  • 14
  • 31