How can I manually / programmatically create a DataRow?

随声附和 提交于 2020-03-21 11:32:44

问题


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.


回答1:


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"] = "elmer@example.com";



回答2:


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.


来源:https://stackoverflow.com/questions/44010345/how-can-i-manually-programmatically-create-a-datarow

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!