Serializing an Arraylist of an ArrayList
I have a DatagridView in my ap开发者_如何学Goplication. I want to serialize the gridview columns into a XML-file. Serializing just the columns name is easy but I want to serialize the columns index too.
Serializing the columns would I do like this:
ArrayList array = new ArrayList();
foreach(DataGridViewColumn column in datagridView1.Columns)
{
array.Add(column.Name)
}
using (FileStream file = new FileStream("test.xml", FileMode.Create))
{
SoapFormatter formatter = new SoapFormatter();
formatter.Serialize(file, array);
}
But I´m wondering how can I serialize the column index too?
Thanks in advance for any help!
Two things to note up front:
- Since you're not creating a soap message, I'd recommend
BinarySerializer
orXmlSerializer
for ad-hoc serialization. - You should definitely prefer a strongly-typed
List<string>
over an untypedArrayList
.
With that said, I'd recommend against serializing altogether -- its too heavyweight for your purposes, and its not a very good approach to long-term storage or transfer of objects (e.g. let's say you serialize a class in v1.0 of your app, then deserialize it in v2.0, all sorts of weirdness can happen).
I'd recommend the following approach: sort your columns by index, then write them out line-by-line to your file. Your columns will be ordered correctly in your file:
using(FileStream file = new FileStream("test.xml", FileMode.Create))
{
var columnNames =
dataGridView1.Columns
.Cast<DataGridViewColumn>()
.OrderBy(x => x.ColumnIndex)
.Select(x => x.Name);
foreach(string column in columnNames)
file.WriteLine(column);
}
Create a public class ColumnInfo with Name and Index and you can store this to array list which can be searialized.
[Serializable]
public class ColumnInfo
{
public string Name;
public int Index;
}
ArrayList array = new ArrayList();
foreach(DataGridViewColumn column in datagridView1.Columns)
{
ColumnInfo ci = new ColumnInfo();
ci.Name = column.Name;
//ci.Index = column.Index; //decide how to get column index
array.Add(ci);
}
using (FileStream file = new FileStream("test.xml", FileMode.Create))
{
SoapFormatter formatter = new SoapFormatter();
formatter.Serialize(file, array);
}
Update I personally use XmlFormater, I copied the source sample from question for example. Thank you abstishchev
精彩评论