DataGridView记录在关闭表单后消失 [英] DataGridView records disappear after closing form
本文介绍了DataGridView记录在关闭表单后消失的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是我的代码:
private void btnInsert_Click(object sender ,EventArgs e)
{
this.dgInsertedInfo.Rows.Add(ddlVendorID.Text,txtDate.Text);
}
解决方案
你有很多选择。这是一个简单的解决方案,它使用 XML序列化。
请注意,它做了几个假设:
- 数据所有都是字符串
- DataGridView已经具有所有列
保存其他数据类型你应该创建一个可序列化的结构!
private void saveButton_Click(object sender,EventArgs e)
{
列表<列表< string>> data = new List< List< string>>();
foreach(dgInsertedInfo.Rows中的DataGridViewRow行)
{
列表< string> rowData = new List< string>();
foreach(row.Cell中的DataGridViewCell单元格)
rowData.Add(cell.FormattedValue.ToString());
data.Add(rowData);
}
XmlSerializer xs = new XmlSerializer(data.GetType());
使用(TextWriter tw = new StreamWriter(yourFileName))
{
xs.Serialize(tw,data);
tw.Close();
}
}
private void loadButton_Click(object sender,EventArgs e)
{
列表<列表< string>> data = new List< List< string>>();
XmlSerializer xs = new XmlSerializer(data.GetType());
using(TextReader tr = new StreamReader(yourFileName))
data =(List< List< string>>)xs.Deserialize(tr);
foreach(List< string>数据中的rowData)
dgInsertedInfo.Rows.Add(rowData.ToArray());
}
I have a datagridview that is not bound to a table in a database. The datagridview is being populated by the contents of a drop down list and a text box on a button click. I want to prevent the records from being deleted everytime I close the form. Is there a way for the records in the datagridview to be saved without having to create a database table?
Below is my code:
private void btnInsert_Click(object sender, EventArgs e)
{
this.dgInsertedInfo.Rows.Add(ddlVendorID.Text, txtDate.Text);
}
解决方案
You have many options. Here is a simple solution that uses XML serialization.
Note that it makes a few assumptions:
- The data all are strings
- The DataGridView already has all the columns
To save the other data types you should create a serializable structure!
private void saveButton_Click(object sender, EventArgs e)
{
List<List<string>> data = new List<List<string>>();
foreach(DataGridViewRow row in dgInsertedInfo.Rows)
{
List<string> rowData = new List<string>();
foreach (DataGridViewCell cell in row.Cells)
rowData.Add(cell.FormattedValue.ToString());
data.Add(rowData);
}
XmlSerializer xs = new XmlSerializer(data.GetType());
using (TextWriter tw = new StreamWriter(yourFileName))
{
xs.Serialize(tw, data);
tw.Close();
}
}
private void loadButton_Click(object sender, EventArgs e)
{
List<List<string>> data = new List<List<string>>();
XmlSerializer xs = new XmlSerializer(data.GetType());
using (TextReader tr = new StreamReader(yourFileName))
data = (List<List<string>>) xs.Deserialize(tr);
foreach (List<string> rowData in data)
dgInsertedInfo.Rows.Add(rowData.ToArray());
}
这篇关于DataGridView记录在关闭表单后消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文