在C#中保存并加载DataGridView内容和样式

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

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

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); } } 

如果有更好的方法来保存内容和样式,也欢迎。 提前致谢

如果您想要持久单元格格式化,则以下类型的对象序列化将适用于您。

创建一个类来序列化您想要的属性:

 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; } } 

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

 public List Settings { get; set; } private void ReadXML() { System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(List)); if (File.Exists(@"SavedSettings.xml")) { System.IO.StreamReader file = new System.IO.StreamReader( @"SavedSettings.xml"); this.Settings = (List)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; } } } 

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

 private void SaveSettings() { this.Settings = new List(); 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)); System.IO.StreamWriter file = new System.IO.StreamWriter(@"SavedSettings.xml"); writer.Serialize(file, this.Settings); file.Close(); } 

注意这将允许某些属性保持不变。 当然有更好的方法,我很乐意在时间允许的情况下学习它们,但这个例子可以完成这项工作。 至于额外的Excel要求,到目前为止我还没有尝试过。 我会补充你的问题,以反映吸引面向Excel的答案的要求。