开发者

read contents of a xml file into a data grid view

开发者 https://www.devze.com 2022-12-26 10:13 出处:网络
Im using c# .net , windows form application. I have a XML file which contains two columns and some rows of data. now i have to fill this data into a data grid view. im using a button, when i click on

Im using c# .net , windows form application. I have a XML file which contains two columns and some rows of data. now i have to fill this data into a data grid view. im using a button, when i click on the button an open dialog box will appear. i have to select the xml file name and when i click on open the contents of that xml f开发者_开发百科ile should come to the data grid view. i have tried with the following code:

{
XmlDataDocument xmlDatadoc=new XmlDataDocument();
XmlDatadoc.Dataset.ReadXml(filename);
ds=xmlDatadoc.Dataset;
datagridview1.DataSource=ds.DefaultViewManager;
datagridview1.Datamember="language";
}

My xml file is:

<languages>
<language>
  <key> key1</key>
<value>value1</value>
</language>

<language>
  <key> key2</key>
<value>value2</value>
</language>
</languages>

Its working fine but only for "language" . I need it to work file other xml files also.


This one's pretty simple: if you want to use this with a different XML file, use a different Datamember property, like so:

datagridview1.Datamember="taxes"; // or whatever

If you're expecting your DataGridView to somehow magically know what elements in your XML to use for rows, you're out of luck.


Hello i this is example, xml must be in correct format, its easy to correct code if needed, that's just the main gist of idea:

        XElement xElement = XElement.Load("file.xml");
        DataTable dTable = new DataTable();
        // keys must have unique name
        xElement.Elements().First().Elements().ToList()
            .ForEach(element=>dTable.Columns.Add(element.Name.ToString()));

        xElement.Elements().ToList().ForEach((item) =>
            {
                // fileds must place in the same order
                // but you can correct it if you want
                var itemToAdd = new List<string>();

                item.Elements().ToList().ForEach(field => itemToAdd.Add(field.Value));
                dTable.Rows.Add(itemToAdd.ToArray()); 
            }
        );

        dataGridView1.DataSource = dTable;
0

精彩评论

暂无评论...
验证码 换一张
取 消