Search code examples
c#.netvisual-studio.net-coresystem.data

System.Data tables data type fix on C#


I have run into an issue with system.data tables where i want to print out each row for each column, however I cant find a way that dose this for mixed data types such as the ones comprised in my table.

here is the relevant code snippet:

table.Rows[0].Field<int>(i)

Which requires a date type after the field classifier, but it breaks my code if its int or string, I need a solution that will work with both as well as bool. And here is the whole class:

public DataTable MakeTable()
{
    using (DataTable table = new DataTable())
    {
        table.Columns.Add("ID", typeof(int));
        table.Columns.Add("First Name", typeof(string));
        table.Columns.Add("Surname", typeof(string));
        table.Columns.Add("Permanent?", typeof(bool));
        table.Columns.Add("Salary", typeof(int));
        table.Columns.Add("Bonus", typeof(int));
        table.Columns.Add("Day Rate", typeof(int));
        table.Columns.Add("Weeks Worked", typeof(int));

        table.Rows.Add(1, "Joe", "Bloggs", true, 40000, 5000, null, null);
        table.Rows.Add(2, "John", "Smith", true, 45000, 2500, null, null);
        table.Rows.Add(3, "Clare", "Jones", false, null, null, 350, 40);
        

        int x = 0;
        for (int i = 0; i < 8; i++)
        {
            Console.WriteLine(table.Columns[i].ColumnName + ":  " + table.Rows[0].Field<int>(i));
            Console.WriteLine();
            if (i == 4)
            {
                x++;
                if (x == 3)
                {
                    Console.WriteLine("BREAK");
                    break;
                }
                i = -1;
            }
            Console.WriteLine("\n");
                
        }
        return table;
    }
}

Any suggestions?

many thanks in advance been stuck on this all day with no avail.


Solution

  • @Alexander

    You may print the data as follows:

    1. table.Rows[i][j] //represents the i-th row and the j-th column.
    2. table.Rows[i]["j"] //represents the data whose column name is j in the ith rows.

    A modified version:

    for (int i = 0, x = 0 ;x< 3; i++) {
         if (i == 8) {
             x++;
             Console.WriteLine("\n");
             i = -1;
             continue;
          }
          Console.WriteLine(table.Columns[i].ColumnName + ":  " + table.Rows[x][i]);
    }
    

    Output result:

    enter image description here

    My demo:

    foreach (DataRow dr in table.Rows) {
    Console.Write("ID:{0,-3} First Name:{1,-5} Surname:{2,-8} Permanent?:{3,-6} Salary:{4,-5} Bonus:{5,-5} Day Rate:{6,-5} Weeks Worked:{7,-5}"//输出格式
    , dr["ID"], dr["First Name"], dr["Surname"], dr["Permanent?"], dr["Salary"], dr["Bonus"], dr["Day Rate"], dr["Weeks Worked"]);
    Console.WriteLine();
    }
    

    Output result:

    enter image description here