Happy coding
Happy coding

Reputation: 51

show xml in datagrid with C#

<customers>
<customer ID="C001">
<name>Acme Inc.</name>
<phone>12345</phone>
<address>value</address>
</customer>
<customer ID="C002">
<name>Star Wars Inc.</name>
<phone>23456</phone>
<address>value</address>
</customer>
</customers>

dataGridView1.DataMember = "customer";

when I put datamember as "customer", it shows all the child nodes of the xml in the datagrid. how to show only ID & name in the grid?

Upvotes: 2

Views: 2243

Answers (4)

Bob
Bob

Reputation: 3

Read the xml using the Dataset then set the Data source of Grid to the dataset table.

Upvotes: 0

crypted
crypted

Reputation: 10306

You can load xml document in grid after that set visibility of required column to true otherwise false.

DataSet data = new DataSet();
            data.ReadXml("C:\\xml.xml");
            this.dataGridView1.DataSource = data;
            this.dataGridView1.DataMember = "customer";
            foreach (DataGridViewColumn column in this.dataGridView1.Columns)
            {
                if (column.Name == "ID" || column.Name == "name")
                    column.Visible = true;
                else
                   column.Visible = false;

            }

Upvotes: 2

Alex Aza
Alex Aza

Reputation: 78447

To show just Id and Name you could do something like this:

var document = XDocument.Load(@"C:\1.xml");

var customers = document.Descendants("customer")
    .Select(arg =>
        new
        {
            Id = arg.Attribute("Id"),
            Name = arg.Descendants("name").Select(x => x.Value).Single()
        })
    .ToList();

dataGridView1.DataSource = customers;

Upvotes: 2

Dmitry Romanov
Dmitry Romanov

Reputation: 14090

You can switch off unneeded columns like:

dataGridView1.Columns["address"].Visible = false; 
//or
dataGridView1.Columns[2].Visible = false; 

It is not the beautiful way for any case. But it is instant.

Upvotes: 1

Related Questions