Winforms sort dataset
Can dsaset ds view be saved to XML file?
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
DataSet ds = new DataSet();
public Form1()
{
InitializeComponent();
ds.ReadXml("file.xml");
dataGridView1.DataSource = ds.Tables[0];
}
private void btnAdd_Click(object sender, EventArgs e)
{
DataRow dr = ds.Tables[0].NewRow();
dr["FN"] = textBox1.Text;
dr["LN"] = textBox2.Text;
ds.Tables[0].Rows.Add(dr);
ds.Tables[0].DefaultView.Sort = "FN asc";
ds.WriteXml("file.xml");
}
}
}
source to share
DataView
class (which is exposed through a DefaultView
property in DataTable
class ) has no mechanism by which it can be serialized and is not persisted when the instance is DataTable
saved.
However, you are better off creating a structure that is serializable (using whichever serialization mechanism you choose) and serialize it DataTable
along with the instance properties DataView
exposed using the property DefaultView
that applies to your application.
However, as mentioned , you can convert the DataView
exposed DefaultView
for the property DataTable
and save it.
source to share
Create a new DataTable from the sorted one DataView
and use its WriteXml method .
ds.Tables[0].DefaultView.Sort = "FN asc";
var sortedTable = ds.Tables[0].DefaultView.ToTable();
sortedTable.WriteXml("file.xml");
source to share