views:

628

answers:

2

Hello. Is there a way to make my program remember the way columns are re-ordered so when the application is re-opened, it orders them the same way as it was when I closed the form. I can't find any properties for this.

Thanks.

+2  A: 

Assuming you are talking about a Windows Forms DataGridView, I'm not aware of any property that would do this for you automatically. I think you could devise a pretty simple scheme by handling the ColumnDisplayIndexChanged Event, though. Whenever the user changes the order of the columns, this event would be triggered, then you could save the column order in an XML file. When first creating the form with the DataGridView, you would need to read the data from the file and set the proper DisplayIndex for each column.

Hope that helps,

-Dan

DanM
Thanks Dan. Do you know where these column settings are kept?
JimDel
You actually have to create the file with the column settings yourself. I was thinking maybe you could create a simple XML file that stores the DisplayIndex for each column. Something like this (sorry for the bad formatting):<columns> <column Index="1" displayIndex="1" /> <column Index="2" displayIndex="4" /> <column Index="3" displayIndex="3" /> <column Index="4" displayIndex="2" /></columns>Then you could just save this file in a Settings folder within your project and read/write to the file as needed.
DanM
+1  A: 

If you don't want to write your own logic you can use the ability of a DataTable to read/write it's data or schema to a xml file.
If you close your form, just create a DataTable, add columns for each DataGridView in the right order and at startup just load this schema and set the order of the columns:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
    }

    // Save order
    private void button1_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable("table");

        var query = from DataGridViewColumn col in dataGridView1.Columns
                    orderby col.DisplayIndex
                    select col;

        foreach (DataGridViewColumn col in query)
        {
            dt.Columns.Add(col.Name);
        }

        dt.WriteXmlSchema(@"c:\temp\columnorder.xml");
    }

    // Restore order
    private void button2_Click(object sender, EventArgs e)
    {
        DataTable dt = new DataTable();
        dt.ReadXmlSchema(@"c:\temp\columnorder.xml");

        int i = 0;
        foreach (DataColumn col in dt.Columns)
        {
            dataGridView1.Columns[col.ColumnName].DisplayIndex = i;
            i++;
        }
    }
}
SchlaWiener