Articles in this section
Category / Section

How to retain the column width after changing the ColumnSizer at run time in Silverlight ?

4 mins read

In SfDataGrid, the ColumnSizer property allows you to specify the column width, based on the data present in the cell and available width. You can define the ColumnSizer property either in the SfDataGrid or Column level.

When you change the ColumnSizer at run time, the column width is calculated based on the type of ColumnSizer.

The following screenshot displays the SfDataGrid loaded with few columns of default width (150) and rest of the widths are set explicitly,

datagrid with columns

Figure 1: Default View

Implement the following, before changing the ColumnSizer.

  • The previous column width should be stored in a separate List.
  • Set double. NAN value to all the columns before changing the ColumnSizer. Since, ColumnSizer is not applied to the columns when the column width is set explicitly. This is the default behavior of ColumnSizer.

You can achieve the above using the following code example.

C#

public static List<double> width1 = new List<double>();
private void Set_Auto(object sender, RoutedEventArgs e)
{
//Save the column width for retaining the resized old width
for (int i = 0; i < this.sfdatagrid.Columns.Count; i++)
{
//Each column ActualWidth is stored to width1
width1.Add(this.sfdatagrid.Columns[i].ActualWidth);
}
foreach (var column in sfdatagrid.Columns)
{
//Reset the width to NAN for applying ColumnSizer as Auto
column.Width = double.NaN;
}
//Set the ColumnSizer as Auto
//The Resized width is stored in to width1 and Auto is applied to column
sfdatagrid.ColumnSizer = GridLengthUnitType.Auto;
}

After changing the ColumnSizer as Auto at runtime, the SfDataGrid’s Columns width is calculated based on the   Auto column sizer as illustrated in the following screenshot.

column width changed

Figure 2: After changing the ColumnSizer as Auto

When you want to retain the column width that was loaded before the ColumnSizer changes, you can achieve it by using the stored List as illustrated in the following code example.

C#

private void Restore_Width(object sender, RoutedEventArgs e)
{
//ColumnSizer=None is changed
sfdatagrid.ColumnSizer = GridLengthUnitType.None;
//Retrieve the width of the column from the value stored in width1
for (int count = 0; count < this.sfdatagrid.Columns.Count; count++)
{
this.sfdatagrid.Columns[count].Width = width1[count];
}
//Clear the old width
width1.Clear();
}

The above code example restores the old width of the columns that is illustrated in the following screenshot.

restore the columns

Figure 3: Restore the old width to Columns

Sample Links

WPF

WRT

SilverLight

UWP

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied