在winform中将textbox,combobox,numericupdown值写入XML [英] Writing textbox, combobox, numericupdown values to XML in winform

查看:78
本文介绍了在winform中将textbox,combobox,numericupdown值写入XML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



目前我正在将文本框,组合框和数字提示的值写入这样的xml;



 XmlWriterSettings settings =  new  XmlWriterSettings(); 
settings.Indent = true ;
settings.IndentChars = \t;
XmlWriter xmlWriter = XmlWriter.Create(PATH,settings);
// 写入XML文件

XmlWriter xmlWriter = XmlWriter .Create(PATH);

xmlWriter.WriteStartElement( NumberOfPeople);
xmlWriter.WriteString(numericUpDown7.Text);
xmlWriter.WriteEndElement();
...



我认为这不是一个很好的方法,因为代码很快就难以维护。是否可以使用foreach遍历表单上的所有控件并获取控件的标签和值,并将其写入xml文件。这样的事情。

 





我尝试过:



  foreach (控制c    this  .Controls)
{
xmlWriter.WriteStartElement(Control.Label);
xmlWriter.WriteString(Control.Text);
xmlWriter.WriteEndElement();
}





编辑1 :(来自解决方案2)

添加编辑,因为我无法在下面的评论中添加代码snipets。

它没有拿起任何控件? XML文件中的所有内容都是;



 <?  xml     version   =  1.0  >  
< ArrayOfLabelValue xmlns:xsd = http ://www.w3.org/2001/XMLSchema xmlns:xsi = http://www.w3.org/2001/XMLSchema-instance / >





编辑2 :(来自解决方案1和2)

i能够获得vlaues文本框,numericUpdowns,comboboxs通过引用显示它们的tableLayoutPanel。通过将其添加到Foreach()

  foreach (控制c  in   this  .mytlp.Controls)

解决方案

仅供参考:

 使用系统; 
使用 System.Collections.Generic;
使用 System.Globalization;
使用 System.IO;
使用 System.Windows.Forms;
使用 System.Xml.Serialization;

命名空间 WindowsFormsApplication5
{
public partial class Form1:Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load( object sender,EventArgs e)
{
var controlsInfo = new List< ControlInfo>();
foreach (控制控件控件中)
{
if (control TextBox || control ComboBox )
{
var controlInfo = new ControlInfo
{
ControlType = control.GetType()。ToString(),
ControlLabel = control.Name,
ControlValue = control.Text
};
controlsInfo.Add(controlInfo);
}
else if (control NumericUpDown)
{
var numericUpDown = control as 的NumericUpDown;
var controlInfo = new ControlInfo
{
ControlType = control。 GetType()。ToString(),
ControlLabel = control.Name,
ControlValue = numericUpDown.Value.ToString(CultureInfo.InvariantCulture)
};
controlsInfo.Add(controlInfo);
}
}

var xmlSerializer = new XmlSerializer( typeof (List< ControlInfo>));
使用 var fileStream = new FileStream( @ d:\ control.xml,FileMode.Create))
{
xmlSerializer.Serialize(fileStream,controlsInfo);
}
}
}

[可序列化]
public class ControlInfo
{
public string ControlType { get ; set ; }
public string ControlLabel { get ; set ; }
public string ControlValue { get ; set ; }
}
}


如果表单有任何更改,请使用此示例并对其进行自定义





 使用系统; 
使用 System.Collections.Generic;
使用 System.IO;
使用 System.Linq;
使用 System.Windows.Forms;
使用 System.Xml.Serialization;

命名空间 WindowsFormsApplication1
{
public class LabelValue
{
public string 标签{ get ; set ; }
public string 值{ get ; set ; }
}
public partial class Form1:Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load( object sender,EventArgs e)
{
}

private void button1_Click( object sender,EventArgs e)
{

Dictionary< string,string> dictLabelValues = new Dictionary< string,string>();
foreach (控制c .Controls)
{
类型controlType = c.GetType();
if (controlType == typeof (Label)|| controlType == typeof (TextBox)|| controlType == typeof (TextBox))
dictLabelValues.Add(c.Name, c.Text);
else if (controlType == typeof (NumericUpDown))
dictLabelValues.Add(c.Name,(c as NumericUpDown).Value.ToString());

}
List< string> lstNames = dictLabelValues.Where(k = > k.Key.StartsWith( lbl))。选择(k = > k.Key.Substring( 3 ))ToList();
列表< LabelValue> list = new List< LabelValue>();
foreach 字符串名称 in lstNames)
{
string label = dictLabelValues。 Single (k = < span class =code-keyword>>
k.Key == lbl + name).Value;
string value = dictLabelValues.FirstOrDefault(k = > k.Key == txt + name || k.Key == cmb + name || k.Key == num + name).Value;
// 使用标签和值在xml中写入。
list .Add( new LabelValue(){Label = label,Value = value });

}

string xmlPath = < span class =code-string> sample.xml
;
var serialiser = new XmlSerializer( typeof < /跨度>(列表与LT; LabelValue>));
使用 var fileStream = new FileStream(xmlPath,FileMode.Create))
{
serialiser.Serialize(fileStream,list);
}
}
}
}


只是一些想法:

  • 将UI的数据模型与UI本身分开是至关重要的。最好不要按照解决方案1或2中描述的方式进行任何操作。



    您必须创建一个从执行中抽象出来的数据模型UI。您的工作流应该抽象出两个步骤:从UI状态填充模型实例并从模型实例填充UI。
  • 甚至不尝试直接使用XML(除非您想开发自己的序列化技术) 。只是不要。相反,使用序列化,但不是过时和可怕的.NET XML序列化(基于ISerializable等)。相反,使用数据合同方法,这是最强大和最容易使用的方法;与其他方法不同,它完全是类型不可知的,非侵入式的,并且是通用的。您只需在任何流中保存任何对象图,然后将其恢复到内存中。



    请参阅:使用数据合同


-SA

Hi,
At the the moment i am writing the values of textboxs,comboboxs and numericupdowns to an xml like this;

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = "\t";
XmlWriter xmlWriter = XmlWriter.Create(PATH, settings);
//Write to XML File

XmlWriter xmlWriter = XmlWriter.Create(PATH);

xmlWriter.WriteStartElement("NumberOfPeople");
xmlWriter.WriteString(numericUpDown7.Text);
xmlWriter.WriteEndElement();
...


I think this is not a good way to do this as the code could quickly become hard to maintain. Would it be possible to use a foreach to go through all the controls on the form and get the labels and the values of the controls and write it to an xml file.Something like this.



What I have tried:

foreach(Control c  in this.Controls)
        {
            xmlWriter.WriteStartElement(Control.Label);
            xmlWriter.WriteString(Control.Text);
            xmlWriter.WriteEndElement();
        }



EDIT 1: (From SOLUTION 2)
Adding edits , because I cant add code snipets in the comments below.
It is not picking up any controls? All that is in the XML file is;

<?xml version="1.0"?>
<ArrayOfLabelValue xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" />



EDIT 2:(From Solution 1 and 2)
i was able to get the vlaues textboxs, numericUpdowns,comboboxs by referencing the tableLayoutPanel in which they are displayed . By adding it to the Foreach()

foreach (Control c in this.mytlp.Controls)

解决方案

Just for sample:

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using System.Xml.Serialization;

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

    private void Form1_Load(object sender, EventArgs e)
    {
      var controlsInfo = new List<ControlInfo>();
      foreach (Control control in Controls)
      {
        if (control is TextBox || control is ComboBox)
        {
          var controlInfo = new ControlInfo
          {
            ControlType = control.GetType().ToString(),
            ControlLabel = control.Name,
            ControlValue = control.Text
          };
          controlsInfo.Add(controlInfo);
        }
        else if (control is NumericUpDown)
        {
          var numericUpDown = control as NumericUpDown;
          var controlInfo = new ControlInfo
          {
            ControlType = control.GetType().ToString(),
            ControlLabel = control.Name,
            ControlValue = numericUpDown.Value.ToString(CultureInfo.InvariantCulture)
          };
          controlsInfo.Add(controlInfo);
        }
      }

      var xmlSerializer = new XmlSerializer(typeof (List<ControlInfo>));
      using (var fileStream = new FileStream(@"d:\controls.xml", FileMode.Create))
      {
        xmlSerializer.Serialize(fileStream, controlsInfo);
      }
    }
  }

  [Serializable]
  public class ControlInfo
  {
    public string ControlType { get; set; }
    public string ControlLabel { get; set; }
    public string ControlValue { get; set; }
  }
}


use this sample and customize it if there is any changes to the Form


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Serialization;

namespace WindowsFormsApplication1
{
    public class LabelValue
    {
        public string Label { get; set; }
        public string Value { get; set; }
    }
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Dictionary<string, string> dictLabelValues = new Dictionary<string, string>();
            foreach (Control c in this.Controls)
            {
                Type controlType = c.GetType();
                if (controlType == typeof(Label) || controlType == typeof(TextBox) || controlType == typeof(TextBox))
                    dictLabelValues.Add(c.Name, c.Text);
                else if (controlType == typeof(NumericUpDown))
                    dictLabelValues.Add(c.Name, (c as NumericUpDown).Value.ToString());

            }
            List<string> lstNames = dictLabelValues.Where(k => k.Key.StartsWith("lbl")).Select(k => k.Key.Substring(3)).ToList();
            List<LabelValue> list = new List<LabelValue>();
            foreach (string name in lstNames)
            {
                string label = dictLabelValues.Single(k => k.Key == "lbl" + name).Value;
                string value = dictLabelValues.FirstOrDefault(k => k.Key == "txt" + name || k.Key == "cmb" + name || k.Key == "num" + name).Value;
                // use the lable and values to write in the xml.
                list.Add(new LabelValue() { Label = label, Value = value });

            }

            string xmlPath = "sample.xml";
            var serialiser = new XmlSerializer(typeof(List<LabelValue>));
            using (var fileStream = new FileStream(xmlPath, FileMode.Create))
            {
                serialiser.Serialize(fileStream, list);
            }
        }
    }
}


Just a couple of ideas:
  • It's critically important to separate the data model of UI from UI itself. Better don't even play with the idea of doing anything the way described on Solution 1 or 2.

    You have to create a data model abstracted from the implementation of the UI. You workflow should abstract out two steps: filling in model instance from UI state and populating the UI from model instance.
  • Don't even try to use XML directly (unless you want to develop your own serialization technology). Just don't. Instead, use serialization, but not obsolete and dreaded .NET XML serialization (based on ISerializable and so on). Instead, use Data Contract approach, which is the most robust and easiest to use; unlike other approaches, it is fully type-agnostic, non-intrusive, and universal. You just save any object graph in any stream and later restore it in memory.

    Please see: Using Data Contracts.

—SA


这篇关于在winform中将textbox,combobox,numericupdown值写入XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆