Binding XML file to DataGridView in Windows Applications with C#

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

  • Thursday, April 20, 2006 9:00 AM
     
     
    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!

All Replies

  • Thursday, April 20, 2006 11:01 AM
     
     

    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 6:23 PM
     
     
    XML can also be loaded to DataSet and then you bind DS to ViewDataGrid.
  • Friday, April 21, 2006 3:02 AM
     
     

    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!

  • Tuesday, April 25, 2006 3:32 PM
     
     

    Use DataGridView bound to XML file.

     

    You can try this;

    XMLDocumentData xmlDoc = new XMLDocumentData();

    xmlDoc.ReadXML(filename);

    DataGridView.DataSource = xmlDoc.Dataset;

  • Thursday, May 11, 2006 10:48 AM
     
     Answered

    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

  • Friday, May 19, 2006 1:44 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

  • Monday, June 12, 2006 1:01 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.

    :)

  • Thursday, December 14, 2006 1:52 PM
     
     

    Hi Did you find the answer for this problem above. Kindly let me know the solution if you do have one.

    Thanks Dudday.

  • Monday, December 18, 2006 11:18 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
    •  
  • Wednesday, March 26, 2008 8:03 AM
     
     

    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

     

  • Saturday, July 24, 2010 5:52 PM
     
      Has Code

    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, September 18, 2010 11:47 AM
     
     

    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
  • Wednesday, November 24, 2010 5:55 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

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