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.
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.
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
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++;
}
}
}