简体   繁体   中英

How to bind datagridview in c# with xml object

I am working on a winform application that use amazon web service. I have made request to get data, the response is in xml object, But i dont know how to bind this xml response with datagridwiew, here is my code..

 private void btnRun_Click(object sender, EventArgs e)
        {
            if (CheckForInternetConnection())
                try
                {
                    // Instantiate Amazon ProductAdvertisingAPI client
                    amazonClient = new AWSECommerceServicePortTypeClient();

                    // prepare an ItemSearch request
                    request = new ItemSearchRequest();

                    request.SearchIndex = "Books";
                    request.Title = "The Life and Love of the Sea";
                    request.ResponseGroup = new string[] { "Small" };

                    itemSearch = new ItemSearch();
                    itemSearch.Request = new ItemSearchRequest[] { request };
                    itemSearch.AWSAccessKeyId = ConfigurationManager.AppSettings["accessKeyId"];
                    itemSearch.AssociateTag = "AssociationTag";

                    // send the ItemSearch request
                    response = amazonClient.ItemSearch(itemSearch);
                    // here i want to bind the datagridview with this xml response.

                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            else
                MessageBox.Show("No Internet Connection found");
        }

First you need to create a DataTable from your xml data and then bind the DataTable to your gridView.

This is the code that i use to create a DataTable from an xml file :

//This method return a dataTable created with your xml data
 public static DataTable  getDataByRessource()
    {
        //Create the new xml document
        XmlDocument xmlDoc = new XmlDocument();

        //Here you can load your file , i load it with the resources properties of my project
        xmlDoc.LoadXml(Properties.Resources.TRADUCTION);
        //This dataSet will contains your dataTable with your data
        DataSet ds = new DataSet();
         //Parse the xml to a dataTable
        XmlNodeReader xnr = new XmlNodeReader(xmlDoc);
        ds.ReadXml(xnr);

        //return your dataTable
        return  ds.Tables[0];
    }

Now you only have to bind the DataSource of your gridView to this DataTable.

EDIT :

Take a look here, it's probably what you want to achieve : http://www.midniteblog.com/?p=20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM