Question

I have DataTable in my application. It holds DataColumns and Rows. I just want to call it recursively and input to InnerXml query. here Field names should be DataColumns values and Value should be Row value of DataTable. Bellow is my tried code. But I don't have idea to iterate DataTable and fill InnerXml.

    DataTable DT = new DataTable();

    for(int i=0 ; i<DT.Length ;i++){
               batchElement.InnerXml =
               "<Method ID='4' Cmd='New'>" + "<Field Name='" + DT.DataColumn[] + "'>" + DT.row + "</Field></Method>";

    }

Please help me.

Was it helpful?

Solution

Do you want to simply enumerate a DataTable or do you actually want to recursively iterate it? I only ask because you example code does not show recursion, it shows enumeration with a couple parts that won't compile.

I'm guessing that you are attempting to serialise the datatable, in which case the following example would probably work:

StringBuilder innerXml = new StringBuilder();
int methodId = 0;
foreach(DataRow row in DT.Rows)
{
    innerXml.AppendFormat("<Method ID='{0}' Cmd='New'>", methodId.ToString());
    methodId += 1;

    foreach(DataColumn column in DT.Columns)
    {
        innerXml.AppendFormat("<Field Name='{0}'>{1}</Field>", column.ColumnName, row[column.ColumnName]);
    }

    innerXml.AppendLine("</Method>");
}
batchElement.InnerXml = innerXml.ToString();

Apologies if the above does not compile - handtyped - should hopefully put you on the right track though.

NB: I'm not really sure, based on your example, how you intend to split the row and cell elements in Xml. I've made some assumptions on the Xml structure but hopefully it's enough for you to work from

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top