views:

1289

answers:

3

I'm trying to set the initial display order of the column headers in a silverlight datagrid by changing the column header DisplayIndex values. If I try to set the column order at page load time, I get an out of range exception. If I set the column order (same routine) at a later time like, in a button click handler, it works. Is this just a bug in the silverlight datagrid control? Suggestions for a possible work around?

+1  A: 

I'm guessing that you've got a problem modifying the DisplayIndex of the columns in the DataGrid from the Page Loaded event as they haven't yet been created at this point. You don't say but I assume you're getting the DataGrid to AutoGenerate your columns as otherwise you could just set the DisplayIndex in your XAML when defining the DataGrid columns.

When the DataGrid generates Columns it fires a AutoGeneratingColumn event for each Column allowing you to modify its properties. It's a little crude but one solution could be to set the DisplayIndex in a handler for this event using the PropertyName it is creating a column for.

private void grid_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    switch (e.PropertyName)
    {
        case "Name":
            e.Column.DisplayIndex = 1;
            break;

        case "Age":
            e.Column.DisplayIndex = 0;
            break;
    }
}
David Padbury
A: 

Thank you for usefull advice, but what if AutoGenerateColumns="False" and I want to read column indexes from file during the page intialization - I keep the user preferencies between sessions. Do you have any suggestions?

A: 

Hi, actually you need to subscribe to grid.Loaded event and reorder colums there:

public UserManagementControl()
    {
        InitializeComponent();
        dataGridUsers.Loaded += new RoutedEventHandler(dataGridUsers_Loaded);
    }

    void dataGridUsers_Loaded(object sender, RoutedEventArgs e)
    {
        dataGridUsers.Columns[0].DisplayIndex = 1;
    }

You've got ArgumentOutOfRangeException because control hadn't been loaded so far

Thunderstorm