我知道这是一个非常简单和基本的问题,但我想知道如何解决这个问题。我在从 datagrdiview 序列化对象时遇到问题。
这条线不适用于我
if (dataGridView1 != null)
_example.Details = dataGridView1.DataBindings; // Not Working.
请告诉我我在这里做的错误是什么......!谢谢你。
private void button3_Click(object sender, EventArgs e) //Read
{
XmlSerializer _serializer = new XmlSerializer(typeof(XMLExample));
XMLExample _example = new XMLExample();
// Read file.
using (TextReader textReader = new StreamReader(@"C:\test\testserialization.xml"))
{
_example = (XMLExample)_serializer.Deserialize(textReader);
textReader.Close();
}
textBox1.Text = _example.ID;
textBox2.Text = _example.Initial;
dataGridView1.DataSource = _example.Details;
}
private void button2_Click(object sender, EventArgs e) //Write
{
XmlSerializer _serializer = new XmlSerializer(typeof(XMLExample));
XMLExample _example = new XMLExample();
_example.ID = textBox1.Text;
_example.Initial = textBox2.Text;
List<Detail> _source = new List<Detail>();
for (int i = 0; i < 10; i++)
{
_source.Add(new Detail
{
FirstName = "Name_" + i,
LastName = "Surname_" + i,
Section = "section_"+i,
});
}
dataGridView1.DataSource = _source;
if (dataGridView1 != null && dataGridView1.DataSource != null)
_example.Details = (List<Detail>)dataGridView1.DataSource;
using (TextWriter textWriter = new StreamWriter(@"C:\test\testserialization.xml"))
{
_serializer.Serialize(textWriter, _example);
textWriter.Close();
}
}
类文件:
[Serializable]
public class StudentInfo : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string UserID { get; set; } // Textbox1
public string Department { get; set; } // Textbox2
public List<Detail> Details { get; set; }
}
[Serializable]
public class Detail // Datagridview1
{
[XmlElement("FirstName")] //Datagridview
public string FirstName { get; set; }
[XmlElement("LastName")] //Datagridview
public string LastName { get; set; }
[XmlElement("Section")] //Datagridview
public string Section { get; set; }
}