Error when trying to hide columns straight after binding data to datagrid

0

So I have an XML file which I read in then display the data onto a DataGrid. Once I bind the DataView of the XML file to the ItemsSource of the datagrid I then attempt to hide the 4th column that will be created (it's an ID which I don't want to show) but receive an error

System.Windows.Markup.XamlParseException
  HResult=0x80131501
  Message='The invocation of the constructor on type 'MoneyLog.MainWindow' that matches the specified binding constraints threw an exception.' Line number '6' and line position '9'.
  Source=PresentationFramework
  StackTrace:
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)

Inner Exception 1:
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

The Code I use:

DataGrid.Columns[4].Visibility = Visibility.Collapsed;

From the error I can see that apparently my number (4) was out of range therefore I assume the table must not of been create yet. To fix this i wrote a crude hack that delays the chunk of code by half a second and this fixes the problem...?

DataGrid.ItemsSource = dataView;
var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) }; 
timer.Start();
timer.Tick += (sender, args) =>
{
     timer.Stop();
     DataGrid.Columns[3].Width = 250;
     DataGrid.Columns[4].Visibility = Visibility.Collapsed;
     DataGrid.CanUserAddRows = false;
     DataGrid.IsReadOnly = true;
};

My question is there another way to do this without this whole timer workaround?

c#
timer
datagrid
dataview
dispatchertimer
asked on Stack Overflow May 18, 2018 by Chris Dworczyk

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0