none
Binding XML file to DataGridView in Windows Applications with C#

    Question

  • Hi,

    Please forgive me if the question is too simple, I am a beginner.

    Part of my application I am working on requires a contact list (similar to the one in Outlook). I decided on the following:

    1.       Create a Class with public properties for the contact details (name, email, phone, etc.).

    2.       Use List<MyContactsClass> to combine each contact into an array.

    3.       Serialize List<MyContactsClass> to XML and store on a disk.

    4.       For retrieval and display, I have two options:

    o        Use DataGridView bound to XML file.

    o        Deserialize XML to my List<MyContactsClass> and bind this to DataGridView.

    I am having trouble with point 4; most topics available suggest using XMLDataSource which is available in ASP.NET, but I need to bind XML in Windows Forms.

    I'd appreciate if someone could help me, and offer some suggestions not only for point 4, but also for the overall design of this portion of the application such as performance and other considerations.

    Thank you in advance!

    Thursday, April 20, 2006 9:00 AM

Answers

  • Hi Migrant

    I think you are looking for this:

        Private Sub LoadBranches()

            Dim filePath As String = (My.Settings.BranchXMLPath)
            Dim BranchDS As New DataSet()
            BranchDS.ReadXml(filePath)
            Try
                With dg_Branches ' the datagridview
                    .DataSource = BranchDS
                    .DataMember = "branch"
                    .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
                    .AutoSize = True
                    .EditMode = DataGridViewEditMode.EditOnEnter
                End With
            Catch ex As Exception
                MsgBox("Branch XML File Could Not Be Loaded: " & ex.Message)
            End Try

        End Sub
        Private Sub btn_SaveBranchList_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_SaveBranchList.Click

            Dim branchDS As New DataSet
            branchDS = dg_Branches.DataSource '  BindingSource1.DataSource
            branchDS.WriteXml(Replace(My.Settings.BranchXMLPath, "branch", "newbranch"))

        End Sub

     

    Cheers!

    Herald

    Thursday, May 11, 2006 10:48 AM

All replies

  • Hello Migrant,

    Your best bet is to deserialise the XML into the list object and bind to that. There is no direct way, that I know of, to bind to xml stored in a file using a DataGrid.

    Data grid is for tables, arrays, and data that's stored in rows and columns. Although XML can be used to store data like that it's not a requirement. XML is like a tree structure than an array. You could try the tree view control, although I don't know if it supports data binding on xml.

    Thursday, April 20, 2006 11:01 AM
  • XML can also be loaded to DataSet and then you bind DS to ViewDataGrid.
    Thursday, April 20, 2006 6:23 PM
  • Thank you for your answer! What I meant was binding xml file to DataGridView by some means (if possible), not directly. I figured out how to bind List<T> object to the Grid by using BindingSource component, such as:

                bindingSource1.DataSource = phoneBook;
                dataGridView1.DataSource = bindingSource1;

    Where phoneBook is the List<T> object. I guess I will try to build a custom component with collapse/expand feature and use an array of such components to display the information. This will give me a chance to learn more aspects of .NET.

    Cheers!

    Friday, April 21, 2006 3:02 AM
  • Use DataGridView bound to XML file.

     

    You can try this;

    XMLDocumentData xmlDoc = new XMLDocumentData();

    xmlDoc.ReadXML(filename);

    DataGridView.DataSource = xmlDoc.Dataset;

    Tuesday, April 25, 2006 3:32 PM
  • Hi Migrant

    I think you are looking for this:

        Private Sub LoadBranches()

            Dim filePath As String = (My.Settings.BranchXMLPath)
            Dim BranchDS As New DataSet()
            BranchDS.ReadXml(filePath)
            Try
                With dg_Branches ' the datagridview
                    .DataSource = BranchDS
                    .DataMember = "branch"
                    .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells
                    .AutoSize = True
                    .EditMode = DataGridViewEditMode.EditOnEnter
                End With
            Catch ex As Exception
                MsgBox("Branch XML File Could Not Be Loaded: " & ex.Message)
            End Try

        End Sub
        Private Sub btn_SaveBranchList_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_SaveBranchList.Click

            Dim branchDS As New DataSet
            branchDS = dg_Branches.DataSource '  BindingSource1.DataSource
            branchDS.WriteXml(Replace(My.Settings.BranchXMLPath, "branch", "newbranch"))

        End Sub

     

    Cheers!

    Herald

    Thursday, May 11, 2006 10:48 AM
  • Thank you Herald, in the end, I decided to create my own "view" object to present the data (User Control). I am sure I will use this feature in the future, so your post is very helpful!

    Regards,

    Migrant

    Friday, May 19, 2006 1:44 AM
  • Hi,

    I posted a tutorial about binding XML to DataGrid at www.KYNOU.com that might help you. Go to the link above and search for: Binding XML to DataGrid

    There is also a chat room there where I try to spend as more time as possible.

    :)

    Monday, June 12, 2006 1:01 AM
  • Hi Did you find the answer for this problem above. Kindly let me know the solution if you do have one.

    Thanks Dudday.

    Thursday, December 14, 2006 1:52 PM
  • If the XML is in a dataset friendly format;

    <document>
      <table>
        <field1>
        . . .
      </table>
      <table>
        <field1>
       . . . 
      </table>
      . . . 
    </document>

    You can use XmlDataDocument which will give you a dataset. Use it just any other dataset. You can even do CRUD using the dataset instead of XML node manipulation. XmlDataDocument inherits from XmlDocument.

     


     

     

    • Proposed as answer by radoslav surov Thursday, August 16, 2012 8:09 AM
    • Unproposed as answer by radoslav surov Thursday, August 16, 2012 8:10 AM
    Monday, December 18, 2006 11:18 PM
  • hi...

     

    i am also having the same prob of binding xml file to datagrid view ... can u pls give me the above code in c#

     

     

    with regards

    Sid

     

    Wednesday, March 26, 2008 8:03 AM
  • If you're looking for a  full LinQ to XML (without DataTables and DataSets) code, try this:

    XDocument xDoc = XDocument.Load("{Path of your XML file}");
    
    var elements = from el in xDoc.Descendants( "{Name of the Element}" )
          select new
          {
           {Name} = el.Element("{Name}").Value,
           ...
           {Name} = el.Element("{Name}").Value 
          };
    
    datagridview.DataSource = elements.ToList();
    
    

    • Edited by Lentucky Saturday, July 24, 2010 5:53 PM Format of the code.
    Saturday, July 24, 2010 5:52 PM
  • Your tutorial gets locked at the point of entering XML data.  I'm interested in going further if you could tell me what I am doing wrong.

    Thank you.


    MarkP
    Saturday, September 18, 2010 11:47 AM
  • To bind a XML file to a Datagridview is really quite simple.
    All u need are 3 lines of code.
    But rember... u can have a lot of datatables in a xml file.

    Here we go:

    1. Set Reference to System.Xml

         System.Xml.

    XmlDataDocument xmlDoc = new XmlDataDocument();
         xmlDoc.DataSet.ReadXml(yourfilename);
         dataGridView1.DataSource = xmlDoc.DataSet.Tables[0]; // index 0 = 1st table in dataset

    u can count all tables in dataset via 

         xmlDoc.DataSet.Tables.Count

    Wednesday, November 24, 2010 5:55 AM
  • This is only true if the XML data is DataSet compatible.
    Tuesday, January 18, 2011 4:57 PM
  • http://www.CodeRND.com/DevelopersFile/Bind-XML-file-to-DataSet-and-display-records-in-a-Grid.aspx
    Tuesday, May 03, 2011 12:23 PM