Search code examples
c#xmldatatabledatasetreadxml

C# retrieving data from DataSet


I have started with a simple DataTable, in which I have written to a XML file. On the next time the program runs, I want to check to see if the XML file exits, and read it.

It appears writing the xml is fine, and I believe reading it is fine, but I cannot seem to get any of the data within the DataSet after I have read from it..

ds.WriteXml(@"C:\Computers\config.xml");
if (File.Exists(@"C:\Computers\config.xml"))
{
    ds.ReadXml(@"C:\Computers\config.xml");
    //comboBox.Items.Add(ds.Tables[0].Rows[0][0].ToString()); doesn't work
    comboBox.Items.Add(ds.Tables[0].Rows.Count);  //this counts 3 rows
}

I receive this error.

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll

Additional information: Cannot find column 1.

here's a look at my XML file

 <?xml version="1.0" standalone="yes"?>
<NewDataSet>
    <Table1>
        <Name>Test1</Name>
        <Version>1.1.1.1</Version>
        <Code />
        <Location>C:\Computers\test.txt</Location>
    </Table1>
    <Table1>
        <Name>test2</Name>
        <Version />
        <Code />
        <Location />
    </Table1>
    <Table1>
        <Name>test3</Name>
        <Version />
        <Code />
        <Location />
    </Table1>
</NewDataSet>        
      

I'm just trying to get the "Name" Field from each row, what am I doing wrong?


Solution

  • I put your XML into C:\computer And run the code

    DataSet ds =new DataSet();
    
    if (File.Exists(@"C:\Computers\config.xml"))
    {
                ds.ReadXml(@"C:\Computers\config.xml");
    
                //comboBox.Items.Add(ds.Tables[0].Rows[0][0].ToString()); doesn't work
                comboBox.Items.Add(ds.Tables[0].Rows.Count);  //this counts 3 rows
    }
    

    comboBox.Items.Add(ds.Tables[0].Rows[0][0].ToString() is Tesy1 ds.Tables[0].Rows.Count is 3

    so, I think problem is not here.