Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I manually / programmatically create a DataRow?

Tags:

c#

system.data

My project's codebase has a legacy method that takes a DataRow as a parameter for which I would like to create a unit test method.

How can I manually create a DataRow object to pass to the method? The System.Data.DataRow class doesn't have a public-facing constructor.

like image 833
Jon Schneider Avatar asked May 16 '17 19:05

Jon Schneider


People also ask

How do you create a DataRow?

To create a new DataRow, use the NewRow method of the DataTable object. After creating a new DataRow, use the Add method to add the new DataRow to the DataRowCollection. Finally, call the AcceptChanges method of the DataTable object to confirm the addition.

How do I add data to DataRow?

After you create a DataTable and define its structure using columns and constraints, you can add new rows of data to the table. To add a new row, declare a new variable as type DataRow. A new DataRow object is returned when you call the NewRow method.

What is the method used to return DataRow?

You use DataTable's NewRow method to return a DataRow object of data table, add values to the data row and add a row to the data Table again by using DataRowCollection's Add method.

What is DataColumn in C#?

DataColumn(String, Type, String, MappingType) Initializes a new instance of the DataColumn class using the specified name, data type, expression, and value that determines whether the column is an attribute.


2 Answers

A DataRow can be created by creating a new DataTable instance, adding columns to the DataTable corresponding to the "keys" that the DataRow needs to have, and then calling NewRow() on the DataTable. For example:

DataTable usersTable = new DataTable();

usersTable.Columns.Add("FirstName");
usersTable.Columns.Add("LastName");
usersTable.Columns.Add("Email");

DataRow userRow = usersTable.NewRow();

userRow["FirstName"] = "Elmer";
userRow["LastName"] = "Example";
userRow["Email"] = "[email protected]";
usersTable.Rows.Add(userRow);
like image 70
Jon Schneider Avatar answered Sep 22 '22 08:09

Jon Schneider


You should note that if the Unit Test needed to enforce type constraints on the DataColumnCollection (Columns) for the DataTable - you can use the overloaded constructor of the DataColumn class to include the expected Type.

        var dt = new DataTable();
        
        var dc = new DataColumn("Age", typeof(int));
        dt.Columns.Add(dc);
        var dr = dt.NewRow();

        dr["Age"] = "test"; // throws an ArgumentException
        //Input string was not in a correct format. Couldn't store<test> in Age Column.  Expected type is Int32.

        //should it succeed
        dt.Rows.Add(dr);
like image 22
Mark C. Avatar answered Sep 20 '22 08:09

Mark C.