Welcome to WindowsClient.net | My Blog | Sign in | Join

Small Business Developer

Sponsors





  • advertise here

Tags

No tags have been created or used yet.

XML And Strongly-Typed Datasets

     This is another interesting item I ran into from the field.  A customer wants to use XML with a DataGridView, but the issue is that they want to manipulate the look of the data in the datagridview during design time.  My solution was to create a strongly-typed dataset and then read the xml into the dataset.  I need to give credit to Rong-Chun Zhang on the MSDN Forums for helping me solve this problem.  Here is the link to the topic at MSDN - http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3543590&SiteID=1  The created project is nothing more than a simple Windows Forms Project.

Source XML

Here is the XML file I used (same as the one from the forum topic)

<MyDataSet xmlns="MyDataSetnamespace">
    <Order_Details>
        <OrderID>10248</OrderID>
        <ProductID>11</ProductID>
        <UnitPrice>14.0000</UnitPrice>
        <Quantity>12</Quantity>
        <Discount>0</Discount>
    </Order_Details>
    <Order_Details>
        <OrderID>10249</OrderID>
        <ProductID>11</ProductID>
        <UnitPrice>14.0000</UnitPrice>
        <Quantity>12</Quantity>
        <Discount>0</Discount>
    </Order_Details>
    <Order_Details>
        <OrderID>10250</OrderID>
        <ProductID>11</ProductID>
        <UnitPrice>14.0000</UnitPrice>
        <Quantity>12</Quantity>
        <Discount>0</Discount>
    </Order_Details>
</MyDataSet>
Strongly-Typed Dataset

Next, you need to create a strongly typed dataset.  What you need to do is add a new item to your project and then select dataset.  Give the dataset a meaningful name and click Add.  This will bring you to the dataset designer.  From there you can add a datatable and all the associated columns.  Here is the result that I had:

image

I saved the changes and now the dataset shows up in the Data Sources Tab.  Now you can add it to your form and manipulate it as you would any other databound datagridview control.

Code Behind

Finally, you need to load the XML into the dataset.  The code is as follows:

Try

  
'You need to set the namespace on the dataset to match the one on the
    'xml file.
  
MyDataSet1.Namespace = "MyDataSetnamespace"

  
MyDataSet1.ReadXml(txtXMLFileLocation.Text)

Catch ex As Exception
    MessageBox.Show(ex.Message)
End Try

This post was really simplistic, but I am going to do more research into how to use more complex XML files with the datagridview, assuming there is any interest. 

Comments

No Comments

Leave a Comment

(required) 

(required) 

(optional)

(required)