Member Avatar for Member #666971

I'm hoping someone here can help me. I am very new to C# and programming in general and am stuck on the following after researching and trying different solutions for the past 2 weeks!

I'm trying to read from an XML file into datagridview. I also want to add extra data that a user inputs into 3 textboxes (an 'add data' button should update datagridview) I'd also like to be able to delete rows from datagridview. On exit, all data is saved into XML file. (I've attached the 'form' design)

The xml file is as follows:

<?xml version="1.0" encoding="utf-8"?>
<Orders_Table>
  <share_order>
    <sharename>bhp</sharename>
    <buyprice>$21.00</buyprice>
    <stopprice>$20.21</stopprice>
    <totalshares>95</totalshares>
	  <totalprice>$1995.00</totalprice>
  </share_order>
  <share_order>
    <sharename>ABC</sharename>
    <buyprice>$23.45</buyprice>
    <stopprice>$19.12</stopprice>
    <totalshares>15</totalshares>
	  <totalprice>$351.75</totalprice>
  </share_order>
</Orders_Table>

I've tried so many different ways to do this that my code is a complete mess, and what I did have working is now broken :icon_cry:

From what I understand, I need to read the XML file into a dataset and then display that dataset in datagridview. I'm not sure where to go from there though.

Can anyone point me in the right direction here? Any tutorials that I can look at?

Thanks in advance

Dani AI

Generated

A focused checklist and small examples to get this working for .

Read the XML into a DataSet, bind a DataTable (not the whole DataSet) to a BindingSource, then bind that BindingSource to the DataGridView. Common problems: the grid was created in the designer with columns that have no DataPropertyName (so nothing appears), the XML path is wrong, or a typed DataSet schema doesn’t match the XML element names. Also note your XML uses “$21.00” — those values will be read as strings; parse them with NumberStyles.Currency when you need numeric math.

Example (binding + save — keep designer columns’ DataPropertyName in sync or set AutoGenerateColumns = true):

var ds = new DataSet();
if (File.Exists(sFile)) ds.ReadXml(sFile);
var table = ds.Tables["share_order"] ?? ds.Tables[0];
bindingSource1.DataSource = table;
dataGridView1.DataSource = bindingSource1;

// commit any pending edit before write
bindingSource1.EndEdit();
ds.WriteXml(sFile, XmlWriteMode.WriteSchema);

Quick troubleshooting steps

  • Verify File.Exists(sFile) and catch any exception text.
  • After ReadXml check ds.Tables.Count and inspect table.Columns to confirm column names.
  • If the grid was pre-populated in the designer, set each column’s DataPropertyName to the XML column names (sharename, buyprice, stopprice, totalshares, totalprice) or enable AutoGenerateColumns.
  • For currency parsing use decimal.TryParse with NumberStyles.Currency and CultureInfo.
    Good pointers were already posted by ; if the problem persists zip the minimal project (form .cs/.designer, Orders.xml, dataset xsd) as suggested so others can reproduce.

Recommended Answers

All 3 Replies

Note that the below are links:

1/.

2/.

3/.

Member Avatar for Member #666971

Thanks! That certainly got me a bit closer. I have added a table to my (untyped) dataset, bound the dataset to the datagrid, however the xml file doesn't populate the grid. I'm sure I'm missing something here:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace LearningDataGridView
{
    public partial class LearningDataGridView : Form
    {
        string sFile = "C:\\Orders.xml";

        public LearningDataGridView()
        {
            InitializeComponent();
        }

        private void btnQuit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void LearningDataGridView_Load(object sender, EventArgs e)
        {
            BindingSource bSource = new BindingSource();
            bSource.DataSource = dsOrders;
            dgOrders.DataSource = bSource;
            
            FileStream fsReadXml = new FileStream(sFile, FileMode.Open);
            try
            {
                dsOrders.ReadXml(fsReadXml);
                this.dgOrders.DataSource = dsOrders.Tables[0].DefaultView;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                fsReadXml.Close();
            }
        }

        private void btnAddData_Click(object sender, EventArgs e)
        {
           // take user input from text boxes and add it to a new row in datagrid
            DataRow drNewRow = dsOrders.Tables[0].NewRow();
            drNewRow[0] = txtShareName.Text;
            drNewRow[1] = txtBuy.Text;
            drNewRow[2] = txtSell.Text;
            drNewRow[3] = txtNumberShares.Text;
            drNewRow[4] = txtTotal.Text;

            dsOrders.Tables[0].Rows.Add(drNewRow);

            //clear text boxes
            txtShareName.Text = "";
            txtBuy.Text = "";
            txtSell.Text = "";
            txtNumberShares.Text = "";
            txtTotal.Text = "";
        }

        private void btnWriteXML_Click(object sender, EventArgs e)
        {
            // save all data in datagrid to XML file
        }

        private void txtNumberShares_TextChanged(object sender, EventArgs e)
        {
            if (txtNumberShares.Text != "")
            {
                txtTotal.Text = Convert.ToString((Convert.ToDecimal(txtBuy.Text)) * (Convert.ToDecimal(txtNumberShares.Text)));
            }
        }

    }
}

How about uploading your project so we can take a look at it?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.