简体   繁体   中英

C# DataRow not Being Added to DataTable

I created a DataTable and when I try to add a row to it, it does not take. I know that there is information in the DataRow, but after the foreach loop is finished, and I look at the DataTable's count, it shows 0. This is the code I'm using:

DataSet CustomColumnsDS = new DataSet();
DataTable dt = new DataTable();
string strXML = GetCatalog(WebUserID, Password); //Web Service Call
XmlDocument doc = new XmlDocument();doc.LoadXml(strXML);
XmlNodeList xnList = doc.SelectNodes("xml/Catalog/item/Package");

if (xnList.Count > 0)//Count = 90
{
dt.Columns.Add("testId", typeof(string));
dt.Columns.Add("testName", typeof(string));

foreach (XmlNode xn in xnList) 
{
    if (!string.IsNullOrEmpty(xn["Id"].InnerText))
    {
        DataRow dr = dt.NewRow();
        dr["testId"] = xn["Id"].InnerText;
        dr["testName"] = xn["Name"].InnerText;
        try
        {
            //At this point the DataRow is filled in with values, but it does not seem to actually add in.
            dt.Rows.Add(dr); //No Exception is caught
        }
        catch (Exception ex)
        {
            string test = "";
        }
    }
}
CustomColumnsDS.Tables.Add(dt);//Count = 0;
}

Any help is appreciated. Thanks!

I ran your code with the following sample xml (in-place of the web service call):

string strXML =
@"
    <xml>
        <Catalog>
            <item>
                <Package>
                    <Id>1</Id>
                    <Name>a</Name>
                </Package>
                <Package>
                    <Id>2</Id>
                    <Name>b</Name>
                </Package>
            </item>
            <item>
                <Package>
                    <Id>3</Id>
                    <Name>c</Name>
                </Package>
                <Package>
                    <Id>4</Id>
                    <Name>d</Name>
                </Package>        
            </item>
        </Catalog>
    </xml>                
    ";

I appended the following code to the end for debugging purposes:

Console.WriteLine(CustomColumnsDS.Tables[0].Rows.Count);

And the output was 4 which is correct. Also viewing the DataTable rows in the debugger revealed that the data is there.

You should try without assign type of column because we do not know the type of xml element, just try: dt.Columns.Add("testId"); dt.Columns.Add("testName"); Until try cacth... Are you sure you get correctly data for every datarow? (run debug until this line to see the value: dr["testName"] = xn["Name"].InnerText;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM