在C#中保存并加载DataGridView内容和样式 [英] Save and load DataGridView Content and Style in C#

查看:314
本文介绍了在C#中保存并加载DataGridView内容和样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有很多列和行的DataGridView,用户可以在单元格中右键单击并从ContextMenuStrip中选择一个选项。选项如红色,蓝色,绿色等颜色,如果用户选择红色,则所选单元格将其BackColor设置为红色,用户还可以在该单元格中写入一个值。那么我的问题是,我找不到一种保存所有内容和样式的方法,所以如果用户重新打开,dataGridView将会有最后的设置(包括单元格的BackColor和ForeColor)。 p>

我尝试保存内容,它给了我错误,我不知道如何打开它。

  private void button4_Click(object sender,EventArgs e)
{
SaveFileDialog svd = new SaveFileDialog();
svd.Filter =XML文件(* .xml)| * .xml;

if(svd.ShowDialog()== System.Windows.Forms.DialogResult.OK)
{
DataTable dt =((DataView)this.dataGridView1.DataSource)。表;
dt.WriteXml(svd.FileName);
}
}

如果有更好的方法来保存内容,风格,也是欢迎的。
感谢提前

解决方案

如果持续单元格格式化是所有您想要的,下列类型的对象序列化将适用于



创建一个类来序列化所需的属性:

  public class SavedSettings 
{
[XmlIgnore]
public Color ForeColor {get;组; }

[XmlElement(ForeColor)]
public int ForeColorARGB
{
get {return this.ForeColor.ToArgb(); }
set {this.ForeColor = Color.FromArgb(value);
}

[XmlIgnore]
public Color BackColor {get;组; }

[XmlElement(BackColor)]
public int BackColorARGB
{
get {return this.BackColor.ToArgb(); }
set {this.BackColor = Color.FromArgb(value); }
}

public object Value {get;组;
}

在你的主类中,从xml加载任何保存的设置:

  public List< SavedSettings>设置{get;组; } 

private void ReadXML()
{
System.Xml.Serialization.XmlSerializer reader =
new System.Xml.Serialization.XmlSerializer(typeof(List< SavedSettings> ;));

if(File.Exists(@SavedSettings.xml))
{
System.IO.StreamReader file = new System.IO.StreamReader(
@ SavedSettings.xml);
this.Settings =(List< SavedSettings>)reader.Deserialize(file);
file.Close();
}
}

private void LoadDGV()
{
this.ReadXML();

if(this.Settings!= null)
{
//这假设你的dgv已经添加了列。
int rows = this.Settings.Count / this.dataGridView1.Columns.Count;
int cols = this.dataGridView1.Columns.Count;

this.dataGridView1.Rows.AddCopies(0,rows); (int i = 0; i< this.Settings.Count; i ++)


{
int row = i / cols;
int col = i%cols;
this.dataGridView1 [col,row] .Style.BackColor = this.Settings [i] .BackColor;
this.dataGridView1 [col,row] .Style.ForeColor = this.Settings [i] .ForeColor;
this.dataGridView1 [col,row] .Value = this.Settings [i] .Value;
}
}
}

然后,当你准备保存,将单元格设置重新加载到对象数组中并将其序列化:

  private void SaveSettings()
{
this.Settings = new List< SavedSettings>();

foreach(this.dataGridView1.Rows中的DataGridViewRow行)
{
if(!row.IsNewRow)
{
foreach(DataGridViewCell单元格中的行.Cells)
{
SavedSettings setting = new SavedSettings();
setting.BackColor = cell.Style.BackColor.ToArgb()== 0? Color.White:cell.Style.BackColor;
setting.ForeColor = cell.Style.ForeColor.ToArgb()== 0? Color.Black:cell.Style.ForeColor; ;
setting.Value = cell.Value;

this.Settings.Add(setting);
}
}
}

this.WriteXML();
}

private void WriteXML()
{
System.Xml.Serialization.XmlSerializer writer =
new System.Xml.Serialization.XmlSerializer(typeof (List< SavedSettings>));

System.IO.StreamWriter file = new System.IO.StreamWriter(@SavedSettings.xml);
writer.Serialize(file,this.Settings);
file.Close();
}

注意这将允许某些属性持续存在。当然有更好的方法,我喜欢随着时间的推移学习,但这个例子可以做这个工作。至于额外的Excel要求,我至今没有尝试过。我会补充你的问题,以反映这个要求,以吸引面向Excel的答案。


I have a DataGridView with many columns and rows, the user is able to right click in a cell and select an option from a ContextMenuStrip. The options are in Colors like Red, Blue, Green, etc, if the user selects, for example, Red, the selected cell sets its BackColor to Red, and the user is also able to write a value in that cell. Well, my problem is that, I cannot find a way to save all the content and style, so if the user re-opens the for, the dataGridView wil have its last settings (including the BackColor and ForeColor of the cells).

I tried this to save the content, it gave me error, and I don't know how to open it.

 private void button4_Click(object sender, EventArgs e)
    {
        SaveFileDialog svd = new SaveFileDialog();
        svd.Filter = "XML Files (*.xml)|*.xml";

        if(svd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            DataTable dt = ((DataView)this.dataGridView1.DataSource).Table;
            dt.WriteXml(svd.FileName);
        }
    }

If there is a better way to save the content and style, it is welcome too. Thanks in Advance

解决方案

If persistent cell formatting is all you want, the following type of object serialization will work for you.

Create a class to serialize your desired properties:

public class SavedSettings
{
    [XmlIgnore]
    public Color ForeColor { get; set; }

    [XmlElement("ForeColor")]
    public int ForeColorARGB
    {
      get { return this.ForeColor.ToArgb(); }
      set { this.ForeColor = Color.FromArgb(value); }
    }

    [XmlIgnore]
    public Color BackColor { get; set; }

    [XmlElement("BackColor")]
    public int BackColorARGB
    {
      get { return this.BackColor.ToArgb(); }
      set { this.BackColor = Color.FromArgb(value); }
    }

    public object Value { get; set; }
}

Within your main class, load any saved settings from xml:

public List<SavedSettings> Settings { get; set; }

private void ReadXML()
{
  System.Xml.Serialization.XmlSerializer reader =
      new System.Xml.Serialization.XmlSerializer(typeof(List<SavedSettings>));

  if (File.Exists(@"SavedSettings.xml"))
  {
    System.IO.StreamReader file = new System.IO.StreamReader(
      @"SavedSettings.xml");
    this.Settings = (List<SavedSettings>)reader.Deserialize(file);
    file.Close();
  }
}

private void LoadDGV()
{
  this.ReadXML();

  if (this.Settings != null)
  {
    // This assumes your dgv has added columns already.
    int rows = this.Settings.Count / this.dataGridView1.Columns.Count;
    int cols = this.dataGridView1.Columns.Count;

    this.dataGridView1.Rows.AddCopies(0, rows);

    for (int i = 0; i < this.Settings.Count; i++)
    {
      int row = i / cols;
      int col = i % cols;
      this.dataGridView1[col, row].Style.BackColor = this.Settings[i].BackColor;
      this.dataGridView1[col, row].Style.ForeColor = this.Settings[i].ForeColor;
      this.dataGridView1[col, row].Value = this.Settings[i].Value;
    }
  }
}

Then, when you're ready to save, reload your cell settings into the object array and serialize it:

private void SaveSettings()
{
  this.Settings = new List<SavedSettings>();

  foreach (DataGridViewRow row in this.dataGridView1.Rows)
  {
    if (!row.IsNewRow)
    {
      foreach (DataGridViewCell cell in row.Cells)
      {
        SavedSettings setting = new SavedSettings();
        setting.BackColor = cell.Style.BackColor.ToArgb() == 0 ? Color.White : cell.Style.BackColor;
        setting.ForeColor = cell.Style.ForeColor.ToArgb() == 0 ? Color.Black :  cell.Style.ForeColor; ;
        setting.Value = cell.Value;

        this.Settings.Add(setting);
      }
    }
  }

  this.WriteXML();
}

private void WriteXML()
{
  System.Xml.Serialization.XmlSerializer writer =
      new System.Xml.Serialization.XmlSerializer(typeof(List<SavedSettings>));

  System.IO.StreamWriter file = new System.IO.StreamWriter(@"SavedSettings.xml");
  writer.Serialize(file, this.Settings);
  file.Close();
}

Note This will allow certain properties to persist. Surely there are better methods and I'd love to learn them as time allows, but this example can do the job. As for the additional Excel requirement, I have not tried that to date. I would supplement your question to reflect that requirement to attract Excel-oriented answers.

这篇关于在C#中保存并加载DataGridView内容和样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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