Working with DataTable in C#

One thing I’ve had to do lately is learn some C#. I will admit that it isn’t the language I would prefer to work with during the week, but it does help me become more versatile when it comes to application development.

Working with C#, I had to take data and enter it into a data grid. Being that I still consider myself a C# newbie, I figured this was something I might as well learn to use.

In the end, creating a data table in C# isn’t that difficult. In this example, I’ll be taking data from a Microsoft Access database and entering it into a DataTable object.

First, let’s define our DataTable and its columns.

Now, while it isn’t necessary, I like having temporary variables to hold data from a database before entering it into our table. For what we have, that would be:

All that is left to get is the data itself. Assuming we’re getting it from some kind of database, we can get the information in a while loop and add all of the data into the table.

Now we have our data in the DataTable. All that is left is to output it. For this, I have a DataGridView object in my form called myDataGrid.

And that’s all there is to using a DataTable in C#.

Have you worked with DataTables? Submit your experiences and comments below!