C# datagridview Columns clear on sort

351 Views Asked by At
        var ds = new DataSet();
        ds.ReadXml(XMLFile);

        DataGridLogView.DataSource = ds.Tables["Header"];
        DataGridLogView.DataMember = "Data";
        DataGridLogView.Columns.Add("5", "Record #");
        DataGridLogView.Columns.Add("6", "Record");

The columns "5" & "6" are the problem columns that i add after my datasource loads in. I can sort any column besides the two i created(5 & 6) but when i sort any of the columns, the two columns i create will clear of all data i add and i cannot seem to figure out why it is doing this. Thanks in advance!

2

There are 2 best solutions below

0
On BEST ANSWER
       datatable.Columns.Add("Record #", typeof(string));
       datatable.Columns.Add("Record", typeof(string));

I had to add the columns to the dataset before setting the datagridviews datasource then the sorting worked perfect.

1
On

With a DataGridView control bound to an external data source, non-data bound cells are not automatically persisted when sorting. Your added columns are not in the dataset, so they get cleared. If your columns "5" and "6" are derived from the row data you might try filling them in the DataGridView.RowsAdded event. Alternatively you could reload those columns in the DataGridView.Sorted event.