将XML加载到网格进行更改并将其保存回来

将XML加载到网格进行更改并将其保存回来

本文介绍了将XML加载到网格进行更改并将其保存回来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!

我将xml加载到datagridview。这是有效的。我做了一些改变后再把它保存下来。这也有效。



现在我添加了一些DataGridViewComboBoxCell。现在,当我在组合框中进行一些更改并将其保存回来时,更改不在xml中。是什么让我错了?



感谢您的帮助!



hi!
I load a xml to a datagridview. this is working. afer I have made some changes I save it back. this also works.

now I have add some DataGridViewComboBoxCell. Now when I make some changes in the combobox and save it back the changes are not in the xml. What make I wrong?

Thanks for your help!

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.Xml;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        DataTable dt = new DataTable();

        DataTable tbl3 = new DataTable();
        DataSet dataSet3 = new DataSet();

        private void getDataSource()
        {
            //dt.Columns.Add("Parameter");
            //dt.Columns.Add("Proc_key 1");
            //dt.Columns.Add("Machine_ID");
            //dt.Columns.Add("Active");

            //dt.Rows.Add("Uniformity", "PM1", "ED2","1");
            //dt.Rows.Add("Uniformity", "PM2", "ED2", "2");
            //dt.Rows.Add("Uniformity_release_hot", "PM1", "ED2", "1");  

            string xmlFile3 = "c:\\Proj\\Epcos\\neo2000\\_versionen\\v11\\Neo2000_Host\\Epcos_Files\\XML\\SPC_Config.xml";
            dataSet3.ReadXml(xmlFile3, XmlReadMode.InferSchema);
            //dataGridView2.DataSource = dataSet2.Tables[0];
            //dataGridView3.DataSource = dataSet3.Tables[0];


        }
        private void Form1_Load(object sender, EventArgs e)
        {
            // just fill the datatable dt
            getDataSource();

            // table dt has four column index 0,1,2,3
            dataGridView1.DataSource = dataSet3.Tables[0];
           // dataGridView1.DataSource = dataSet3;

            tbl3 = dataSet3.Tables[0];
            //DataGridViewColumn column = dataGridView1.Columns[0];
            //column.Width = 200;

            // create Combo Box Cell PROC_KEY 1

            DataGridViewComboBoxCell bc1 = new DataGridViewComboBoxCell();

            //if want to add the fix value in ComboBox
            bc1.Items.AddRange("PM1", "PM2");
            //Add new colum to grid with Combobox
            DataGridViewColumn cc1 = new DataGridViewColumn(bc1);
            dataGridView1.Columns.Add(cc1);
            //Add Header from old column to new column with combobox
            dataGridView1.Columns[4].HeaderText = dataGridView1.Columns[1].HeaderText;
            // set the value in combobox
            foreach (DataGridViewRow item in dataGridView1.Rows)
            {
                item.Cells[4].Value = item.Cells[1].Value;
            }
            //Disable old Column - so only new column with combobox will be displayed
            dataGridView1.Columns[1].Visible = false;
            dataGridView1.Columns[4].ToolTipText = "Select Module";

            //----------------------------------------------------------------------------------
            //Same routin for other Column (MACHINE_ID)
            DataGridViewComboBoxCell bc2 = new DataGridViewComboBoxCell();
            //if want to add the fix value in ComboBox
            bc2.Items.AddRange("ED1", "ED2");
            //Add new column to grid with Combobox
            DataGridViewColumn cc2 = new DataGridViewColumn(bc2);
            dataGridView1.Columns.Add(cc2);
            //Add Header from old Column to new column with combobox
            dataGridView1.Columns[5].HeaderText = dataGridView1.Columns[2].HeaderText;
            // set the value in combobox
            foreach (DataGridViewRow item in dataGridView1.Rows)
            {
                item.Cells[5].Value = item.Cells[2].Value;
            }
            //Disable old Column - so only new column with combobox will be displayed
            dataGridView1.Columns[2].Visible = false;
            dataGridView1.Columns[5].ToolTipText = "Select Equipment";

            //----------------------------------------------------------------------------------
            //Same routin for other Column (MACHINE_ID)
            DataGridViewComboBoxCell bc3 = new DataGridViewComboBoxCell();
            //if want to add the fix value in ComboBox
            bc3.Items.AddRange("1", "2");
            DataGridViewColumn cc3 = new DataGridViewColumn(bc3);
            dataGridView1.Columns.Add(cc3);
            //Add Header from old column to new colun with combobox
            dataGridView1.Columns[6].HeaderText = dataGridView1.Columns[3].HeaderText;
            // set the value in combobox
            foreach (DataGridViewRow item in dataGridView1.Rows)
            {
                item.Cells[6].Value = item.Cells[3].Value;
            }
            //Disable old Column - so only new column with combobox will be displayed
            dataGridView1.Columns[3].Visible = false;
            dataGridView1.Columns[6].ToolTipText = "1=active | 2=inactive";

            /*  if you want to get the existing value in gender column
             *	and display them in ComboBox
             */
            // var ss = dt.AsEnumerable()
            //           .Select(_ => _.Field<string>("gender")).
            //           .Distinct();
            // bc.Items.AddRange(ss.ToArray());

        }

        private void btn_saveXML_Click(object sender, EventArgs e)
        {

            string path = "Config_neu.xml";
            DataSet ds = new DataSet();
            ds = ((DataTable)dataGridView1.DataSource).DataSet;
            ds.Tables[0].WriteXml(path, System.Data.XmlWriteMode.IgnoreSchema);


        }
    }
}





什么我试过了:



我在互联网上搜索并检查了一些变化但没有任何效果。



What I have tried:

I have searched in the internet and check some changes but nothing works.

推荐答案

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace TestForm1
{
    /// <summary>
    /// Test data grid with BindingList.
    /// Replace column with ComboBox.
    /// Replace date column with class CalendarColumn.
    /// </summary>
    public partial class Form5 : Form
    {
        public BindingList<dgvClass1> bindingList;

        public Form5()
        {
            InitializeComponent();

            // Allow user to resize column widths.
            this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
            this.dataGridView1.AllowUserToAddRows = false;

            this.dataGridView1.DataBindingComplete += (s, ev) => Debug.WriteLine("BindingComplete");
            //this.dataGridView1.CurrentCellDirtyStateChanged += new DataGridViewRowEventHandler(this.DataGridChanged);
            this.dataGridView1.CellValueChanged += new DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
            this.dataGridView1.RowValidated += new DataGridViewCellEventHandler(this.RowValidatedEvent);
        }

        /// <summary>
        /// Fill the BindingList and set the dataGridView1.DataSource.
        /// See:
        /// http://stackoverflow.com/questions/21333320/converting-column-in-datagridview-into-a-combobox
        /// http://www.codeproject.com/Articles/24656/A-Detailed-Data-Binding-Tutorial
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            bindingList = new BindingList<dgvClass1>();
            bindingList.AllowNew = true;
            bindingList.AllowRemove = true;

            if (this.dataGridView1.DataSource != null)
            {
                this.dataGridView1.DataSource = null;
                this.dataGridView1.Columns.Remove("Priority");
            }

            this.AddTestData();
            this.AddComboBox();
            this.AddCalendarColumn();

            bindingList.AddingNew += (s, ev) => Debug.WriteLine("AddingNew");
            bindingList.ListChanged += (s, ev) => Debug.WriteLine("ListChanged");
        }

        /// <summary>
        /// http://www.codeproject.com/Articles/38972/Nullable-datetime-column-in-NET-DataGrid-with-Date
        /// </summary>
        private void AddTestData()
        {
            // Add row with test data.
            var item = new dgvClass1();
            item.Number = 1;
            item.Name = "Test data1";
            item.priority = "Low";          // Not visible field will be used in ComboBox later.
            bindingList.Add(item);

            // Add row with test data.
            item = new dgvClass1();
            item.Number = 2;
            item.Name = "Test data2";
            item.date = item.date.AddMonths(1);
            bindingList.Add(item);

            // Add row with test data.
            item = new dgvClass1();
            item.Number = 3;
            item.Name = "Test data3";
            item.date = item.date.AddMonths(2);
            bindingList.Add(item);

            var clone = (dgvClass1)item.Clone();
            clone.Number++;
            bindingList.Add(clone);

            clone = (dgvClass1)clone.Clone();
            clone.Number++;
            bindingList.Add(clone);

            this.dataGridView1.DataSource = bindingList;
            this.dataGridView1.Columns[0].Frozen = true;

            //this.dataGridView1.Columns[1].ValueType = typeof(int); 
        }

        /// <summary>
        /// Add ComboBox column at position 2.
        /// </summary>
        private void AddComboBox()
        {
            DataGridViewComboBoxColumn dgvCombo = new DataGridViewComboBoxColumn();
            dgvCombo.Name = "Priority";
            dgvCombo.Width = 100;
            dgvCombo.DataSource = new string[] { "Low", "Medium", "High" };
            dgvCombo.DisplayIndex = 2;
            this.dataGridView1.Columns.Add(dgvCombo);

            for (int rowNr = 0; rowNr < bindingList.Count; rowNr++)
            {
                var row = this.dataGridView1.Rows[rowNr];
                DataGridViewComboBoxCell dgvComboCell = (DataGridViewComboBoxCell)row.Cells["Priority"];
                dgvComboCell.Value = bindingList[row.Index].priority;
            }
        }

        /// <summary>
        /// Uses class CalendarColumn.
        /// https://msdn.microsoft.com/en-us/library/7tas5c80(v=vs.100).aspx
        /// </summary>
        private void AddCalendarColumn()
        {
            CalendarColumn col = new CalendarColumn();
            col.Name = "Datum";
            col.Width = 100;
            this.dataGridView1.Columns.Add(col);
            ////this.dataGridView1.Columns["Datum"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm";   // "dd/MM/yyyy";

            foreach (DataGridViewRow row in this.dataGridView1.Rows)
            {
                row.Cells["Datum"].Value = bindingList[row.Index].date;
            }
        }

        public void DataGridChanged(object sender, DataGridViewRowEventArgs e)
        {
            Debug.Print("CollectionChanged");
        }

        private void RowValidatedEvent(object sender, DataGridViewCellEventArgs e)
        {
            Debug.Print("RowValidatedEvent");
        }

        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Priority")
            {
                string oldPriority = this.bindingList[e.RowIndex].priority;
                string newPriority = this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                this.bindingList[e.RowIndex].priority = newPriority;
                //this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Style.BackColor = Color.Yellow;
                Debug.Print("Priority changed from: " + oldPriority + " to: " + newPriority);
            }
            else if (this.dataGridView1.Columns[e.ColumnIndex].Name == "Datum")
            {
                ////DateTime oldDate = this.bindingList[e.RowIndex].date;
                DateTime newDate;
                DateTime.TryParse(this.dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(), out newDate);
                this.bindingList[e.RowIndex].date = newDate;
            }
        }

        /// <summary>
        /// Show changes in bindingList.
        /// </summary>
        private void button2_Click(object sender, EventArgs e)
        {
            string str = string.Empty;

            foreach (var item in this.bindingList)
            {
                str += item.Name + ", " + item.priority + ", " + item.date + "\n";
            }

            MessageBox.Show(str);
        }

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            if (this.dataGridView1.CurrentRow != null)
            {
                this.bindingList.RemoveAt(this.dataGridView1.CurrentRow.Index);
            }
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            var item = new dgvClass1();
            bindingList.Add(item);
            this.dataGridView1.Rows[this.bindingList.Count - 1].Cells["Priority"].Value = item.priority;    // "Medium"
            this.dataGridView1.Rows[this.bindingList.Count - 1].Cells["Datum"].Value = item.date;
        }
    }
}

///////////////////////// And the helper class:

    public class dgvClass1 : ICloneable
    {
        /// <summary>
        /// priority is not a propery, so it is not visible in datagrid by default.
        /// </summary>
        public string priority;

        /// <summary>
        /// date is not a propery, so it is not visible in datagrid by default.
        /// </summary>
        public DateTime date;

        public int Number { get; set; }
        public string Name { get; set; }

        public dgvClass1()
        {
            this.date = DateTime.Now;
            this.priority = "Medium";
        }

        /// <summary>
        /// https://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.100).aspx
        /// </summary>
        public object Clone()
        {
            return (dgvClass1)this.MemberwiseClone();
        }
    }


这篇关于将XML加载到网格进行更改并将其保存回来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 20:53