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

      

+3


source to share


3 answers


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.

0


source


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

      

0


source


Call DataTable.DefaultView.ToTable()

and then use the table method WriteXml()

. I believe the sort order will be preserved.

0


source







All Articles