Me n My Programming

If Only I Have TIme

How I populate my dataGridView

For the past few days, I have been battling with C# to populate my xml file inside a dataGridView. Yes, it is not easy and there is a better way to do this, but this is how I do it right now.

1. Sample.xml

<?xml version=”1.0″ encoding=”utf-8″?>
<project id=”1″ name=”BookStore” domain=”POS”>
<class id=”1″ name=”Customer” relationship=”inheritance”>
<attribute>
<id>1</id>
<name>customerName</name>
<type>string</type>
<behavior>-</behavior>
</attribute>
<attribute>
<id>2</id>
<name>customerAddress</name>
<type>string</type>
<behavior>-</behavior>
</attribute>
<method>
<id>1</id>
<name>Print_Customer_Name</name>
<type>public</type>
<parameter>2</parameter>
</method>
<method>
<id>2</id>
<name>Print_Customer_Address</name>
<type>public</type>
<parameter>2</parameter>
</method>
</class>
<class id=”2″ name=”Books” relationship=”aggregation”>
<attribute>
<id>1</id>
<name>bookTitle</name>
<type>string</type>
<behavior>-</behavior>
</attribute>
<method>
<id>1</id>
<name>Print_Book_Title</name>
<type>private</type>
<parameter>3</parameter>
</method>
</class>
</project>

2. Program.cs – (I did cut a few corner but you know the important part)

projectDoc = new XmlDocument();
projectDoc.Load(“Sample.xml”);
projectDoc.Normalize();

String selected = comboBox2.SelectedItem.ToString();
XPathNavigator nav = ((IXPathNavigable)projectDoc).CreateNavigator();
String expr = “/project/class[@name='”+selected+”‘]/attribute”;
XPathNodeIterator iter = nav.Select(expr);

XmlNodeList nodes = projectDoc.SelectNodes(expr);

for (int i = 0; i < nodes.Count; i++)
{
XmlNodeList x = nodes[i].ChildNodes;
object[] data = {(object)x.Item(0).InnerText, (object)x.Item(1).InnerText, (object)x.Item(2).InnerText, (object)x.Item(3).InnerText};
dataGridView1.Rows.Add(data);
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Information

This entry was posted on June 10, 2008 by in C# and tagged , .
%d bloggers like this: