Tuesday, February 15, 2005

Adding a new DataRow to a DataTable

This is one little item that I never can seem to remember, because I just do not use it that often, so I thought I would commit it to my blog.

When creating a new DataRow that you want to subsequently add to a DataTable, you generally create the columns that you need for the rows and then you add data values. The code for this looks something like this...

    DataTable ErrorTable = new DataTable();
    ErrorTable.Columns.Add(new DataColumn("Fault Code Namespace", typeof(string)));
    ErrorTable.Columns.Add(new DataColumn("Fault Code Name", typeof(string)));
    ErrorTable.Columns.Add(new DataColumn("SOAP Actor that threw Exception", typeof(string)));
    ErrorTable.Columns.Add(new DataColumn("Error Message", typeof(string)));
    ErrorTable.Columns.Add(new DataColumn("Detail", typeof(string)));
    DataRow row = ErrorTable.NewRow();
    row["Fault Code Namespace"] = error.Code.Namespace;
    row["Fault Code Name"] = error.Code.Name;
    row["SOAP Actor that threw Exception"] = error.Actor;
    row["Error Message"] = error.Message;
    row["Detail"] = HttpUtility.HtmlEncode(error.Detail.OuterXml);


There is a simpler way to write the code above which sets up the data values and adds the DataRow to the DataTable. That code can be written in one line like this...

    ErrorTable.Rows.Add( new object[] {error.Code.Namespace, error.Code.Name, error.Actor,
    error.Message, HttpUtility.HtmlEncode(error.Detail.OuterXml)} );


The code is definitely not more readable and is probably more of a headache for someone to come along later and maintain, but it is easier to type the first time around. :)

Technorati Tags: , , ,

No comments: