473,320 Members | 2,000 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,320 developers and data experts.

Load a DataSet (or DataTable) from a 2D array of objects

GaryTexmo
1,501 Expert 1GB
NOTE: The source for the utility class is included as an attachment. See the end of this post for details.

So from time to time I've needed to work with DataSets, either to prototype something or just experiment with them and I've always found it a pain to create them. Visual Studio has a designer, but I've always found you need to connect to a database (or an Access file) to create them, which is more than I want to do when I need some quick data to play around with.

To that end, I made a little utility to allow me to define some data in a 2D array, keep a list of those, and then load them as tables into a DataSet. I realize there are likely many ways to do this, but I've found this works for me and since I've found it fairly useful, I wanted to share it in hopes that other people get some use out of it too.

The utility I've created supports both untyped data (defined as a string and loaded in as such) or typed data (types specified, loads the specified data type). It's a static, global class with methods on it to get data. The namespace is DataFactories and the class is DataFactory. The methods available are...

Expand|Select|Wrap|Line Numbers
  1. /// <summary>
  2. /// Builds the sample data from a list of table definitions.
  3. /// </summary>
  4. /// <param name="tableDefinitions">The TableDefinitions object containing the table data.</param>
  5. /// <param name="columnRow">The row specifying the column. Optional, defaults to 0.</param>
  6. /// <param name="typeRow">The row specifying the types. Optional, defaults to -1 (no types define, defaulting to string data).</param>
  7. /// <param name="dataSetName">The name of the data set. Optional, defaults to no name.</param>
  8. /// <returns>A DataSet containing the created DataTable objects.</returns>
  9. public static DataSet BuildDataSet(TableDefinitions tableDefinitions, int columnRow = 0, int typeRow = -1, string dataSetName = "")
  10.  
  11. /// <summary>
  12. /// Builds the sample data from a list of table definitions.
  13. /// </summary>
  14. /// <param name="tableDefinitions">The list of table definitions.</param>
  15. /// <param name="columnRow">The row specifying the column. Optional, defaults to 0.</param>
  16. /// <param name="typeRow">The row specifying the types. Optional, defaults to -1 (no types define, defaulting to string data).</param>
  17. /// <param name="dataSetName">The name of the data set. Optional, defaults to no name.</param>
  18. /// <returns>A DataSet containing the created DataTable objects.</returns>
  19. public static DataSet BuildDataSet(List<KeyValuePair<string, object[][]>> tableDefinitions, int columnRow = 0, int typeRow = -1, string dataSetName = "")
  20.  
  21. /// <summary>
  22. /// Creates a DataTable from the parameters provided.
  23. /// </summary>
  24. /// <param name="tableName">The name of the table to create.</param>
  25. /// <param name="rawDataTable">The definition of the table.</param>
  26. /// <param name="columnRow">The row number the column names can be found on (typically the first row).</param>
  27. /// <param name="typeRow">The row number the types can be found on. Set this to -1 if all types are to be strings.</param>
  28. /// <returns></returns>
  29. public static DataTable BuildDataTable(string tableName, object[][] rawDataTable, int columnRow = 0, int typeRow = -1)
The best way I find to use this is, in my project, to create a new class called SampleData. In this class I provide a static method that returns all the data I want to load. I'll create this for every solution I need a data set in to customize the data I get back. Now for the actual data... I define it as a two dimension array and this lets me set it up to look like, making it easy to read. As I mentioned previously, the utility supports loading two kinds of data, string data and typed data, so lets look at an example using string data.

Lets say I've got an employee table... so maybe I'll do something like this...
Expand|Select|Wrap|Line Numbers
  1. private static string[][] RAW_EMPLOYEES = new string[][]
  2. {
  3.     new string[] { "ID",        "FIRST_NAME",       "LAST_NAME" },
  4.     //              ------------------------------------------
  5.     new string[] { "1",         "Gary",             "Texmo" },
  6.     new string[] { "2",         "Joe",              "Smith" },
  7.     new string[] { "3",         "Jane",             "Doe" }
  8. };
Note that I've defined the columns in my first row. The methods will default to row zero as the column row, but you can define the columns in whatever row you like as long as you specify it. These are the names that will be used for the columns in the data set.

Now, the DataFactory.BuildDataSet method's tableDefinitions parameter is of type List<KeyValuePair<string, object[][]>>. This allows us to set up a list of tables, providing a string name for the table, and a 2D array of data for that table. To create this table definitions parameter, we do...

Expand|Select|Wrap|Line Numbers
  1. List<KeyValuePair<string, object[][]>> tableDefinitions = new List<KeyValuePair<string, object[][]>>()
  2. {
  3.     new KeyValuePair<string, object[][]>("EMPLOYEES", RAW_EMPLOYEES)
  4. };
... adding lines as needed for more tables. We would then load the DataSet by calling the BuildDataSet method as such:

Expand|Select|Wrap|Line Numbers
  1. DataSet data = DataFactory.BuildDataSet(tableDefinitions);
Because this data type can be a little confusing to some people, I've created another utility class to store a list of these KeyValuePair<string, object[][]> objects and an overload method to take in that object. So as an alternative to the above, we can do the following...

Expand|Select|Wrap|Line Numbers
  1. TableDefinitions tableDefinitions = new TableDefinitions();
  2. tableDefinitions.Add("EMPLOYEES", RAW_EMPLOYEES);
  3.  
  4. DataSet data = DataFactory.BuildDataSet(tableDefinitions);
Use whichever you find easier. Anyway, now we have a class that will load our sample data and return a DataSet object.

Expand|Select|Wrap|Line Numbers
  1. public class SampleData
  2. {
  3.     private static string[][] RAW_EMPLOYEES = new string[][]
  4.     {
  5.         new string[] { "ID",        "FIRST_NAME",       "LAST_NAME" },
  6.         //              ------------------------------------------
  7.         new string[] { "1",         "Gary",             "Texmo" },
  8.         new string[] { "2",         "Joe",              "Smith" },
  9.         new string[] { "3",         "Jane",             "Doe" }
  10.     };
  11.  
  12.     public static DataSet GetSampleData()
  13.     {
  14.         TableDefinitions tableDefinitions = new TableDefinitions();
  15.         tableDefinitions.Add("EMPLOYEES", RAW_EMPLOYEES);
  16.  
  17.         return DataFactory.BuildDataSet(tableDefinitions);
  18.     }
  19. }
We can now call this anywhere in our program. It's a good idea to put it in a try/catch block as I throw several exceptions when errors are encountered.

Expand|Select|Wrap|Line Numbers
  1. try
  2. {
  3.     DataSet data = SampleData.GetSampleData();
  4. }
  5. catch (Exception e)
  6. {
  7.     Console.WriteLine(e.Message);
  8. }
If you put a breakpoint in there and use the VisualStudio DataSet Visualizer (hover over the DataSet object and click the magnifying glass), we see the following...



Now, as I mentioned, I also support loading typed data so lets say we wanted the ID column in our data to be an integer data type. We'll need to change our array from string[][] to object[][], define a row of types, and then our data. The methods on the DataFactory class take a parameter that defines what row the types are located on. This defaults to -1, which signifies that types are not defined and that column data is strings.

So our modified object array, with types, would look like...

Expand|Select|Wrap|Line Numbers
  1. private static object[][] RAW_EMPLOYEES = new object[][]
  2. {
  3.     new object[] { "ID",        "FIRST_NAME",       "LAST_NAME" },
  4.     new object[] { typeof(int), typeof(string),     typeof(string) },
  5.     //              ------------------------------------------
  6.     new object[] {  1,         "Gary",             "Texmo" },
  7.     new object[] {  2,         "Joe",              "Smith" },
  8.     new object[] {  3,         "Jane",             "Doe" }
  9. };
Note the second row, defining the types for each column. We can now change our call to BuildDataSet to specify that the column row is 0 and the type row is 1.

Expand|Select|Wrap|Line Numbers
  1. return DataFactory.BuildDataSet(tableDefinitions, 0, 1);
If we were to inspect the data set and look at the data type of the column, we'll be able to see that it's now an integer (vs. the string type it was before).



As you need more tables, you simply create more 2D arrays and add them to the tableDefinitions object. They will all get loaded into the DataSet in the Tables property and you can access them by name (or index).

So there we go, fairly easy to define and load data sets in order to provide sample data for our programs to work with. If, later on, you get a database connection, you can simply replace your sample data sets with the results from your database queries and your program should be able to continue on.

Because I'm a big believer in source sharing, I'm not going to provide a dll for this but instead am attaching the source code for it. Please see the attachment list for DataFactory.cs.txt. Rename this to DataFactory.cs and place it in your project, or in a new project within your solution.

If you have any questions/comments, please feel free to post them.

Thanks!
Attached Images
File Type: png ds_result_str.PNG (5.4 KB, 3132 views)
File Type: jpg ds_coltype.jpg (53.0 KB, 2985 views)
Attached Files
File Type: txt DataFactory.cs.txt (10.3 KB, 1302 views)
Jun 24 '11 #1
0 8365

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: DaveF | last post by:
I have a dataset with an unknown amount of fields. The user can choose a nuber of numeric fields in that datatable. I am making a chart out of those fields. I need to know the minimum and maximun...
10
by: Bernie Yaeger | last post by:
I have a need to add a primary key to a dataset/datatable. How can this be done using a standard oledb data provider? Tx for any help.
1
by: abc my vclass | last post by:
Is VS2005 debugger let me to see dataset, datatable data as table form? I found if I watch some table or dataset variable is very very hard to see. Is there any good tools or add-ins for debugger...
0
by: AboutJAV | last post by:
Hi, I added a datagrid. When the user make changes to the cells, the datatable was updated with the new values. I need to update the dataset.datatable with the current datatable, but an error...
2
by: Mr. Arnold | last post by:
I am working a C# project that uses what's in the subject. I kind of have the basics down on reading the table data. I don't use the above methods of data access or persistence, but I am stuck...
1
by: Daniel Jeffrey | last post by:
..Net 2.0 VStudio 2005 C# I know this is going to seem like a strange question, as even I am sure I have missed something - but I cant find it. I want a simple event on any of the objects...
1
nev
by: nev | last post by:
dataset.datatable.adddatatablerow("john", "rambo") datatabletableadapter.update(dataset.datatable) when i view my mysql table using navicat, the row was not added. i tried adding...
3
by: ASPnewb1 | last post by:
I am currently filling a dataTable then adding this table to a dataset, setting the dataset to the Gridview's datasource. If I set the Gridview to generate columns automatically it will fill the...
4
by: =?Utf-8?B?RnJhbmsgVXJheQ==?= | last post by:
Hi all I have a DataSet with one table filled. From this DataSet (DataTable), I need to create a SqlDataReader. Does anybody knows how to do this ? Is it possible ?? Thanks for any help.
5
by: ravno | last post by:
I am developing a Windows-application - database mssql - visual basic. I add Datasets to forms, bind them to daatagridview/textboxes - fill with dataadapter - everything's fine so far. Here's my...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.