Live Chat Icon For mobile
Live Chat Icon

How do I rearrange the columns in a DataGrid ?

Platform: WPF| Category: Annotations

The columns appear in the order in which their column styles were added to the tablestyle, being used by the grid. If you want to change this order, you need to create a new table style and add the column styles in the order you want things to appear.

Here are some code snippets that suggest how to do this.

[C#]

public void MoveColumn(DataGrid _dataGrid, string _mappingName, int fromCol, int toCol)
{
if(fromCol == toCol) return;
DataGridTableStyle oldTS = _dataGrid.TableStyles[_mappingName];
DataGridTableStyle newTS = new DataGridTableStyle();
newTS.MappingName = _mappingName;
for(int i = 0; i < oldTS.GridColumnStyles.Count; ++i)
{
if(i != fromCol && fromCol < toCol)
newTS.GridColumnStyles.Add(oldTS.GridColumnStyles[i]);
if(i == toCol)
newTS.GridColumnStyles.Add(oldTS.GridColumnStyles[fromCol]);
if(i != fromCol && fromCol > toCol)
newTS.GridColumnStyles.Add(oldTS.GridColumnStyles[i]);
}
_dataGrid.TableStyles.Remove(oldTS);
_dataGrid.TableStyles.Add(newTS);
}
Sample usage
private void button1_Click(object sender, System.EventArgs e)
{
MoveColumn( myDataGrid, 'Customers', 3, 1 );
}

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.