When I have a simple DataSet that has a table with simple column names (i.e., no spaces or periods), code such as the following works just fine:
DataGrid resultsGrid=...; // Actually defined in the XAML
DataSet ds=...; // The is the DataSet that contains one table
Binding binding = new Binding();
resultsGrid.DataContext=ds.Tables[0];
resultsGrid.SetBinding(DataGrid.ItemsSourceProperty, binding);
The DataGrid in the above example has the AutoGenerateColumns attribute set to True and properly populates its data from the table in the DataSet.
However, if my table has columns with names containing spaces / periods or other special characters, the automated binding seems to fail. I get errors such as:
System.Windows.Data Information: 20 : BindingExpression cannot
retrieve value due to missing information. BindingExpression:Path=My
Col. Name; DataItem=’DataRowView’ (HashCode=8146871); target element
is ‘TextBlock’ (Name=”); target property is ‘Text’ (type ‘String’)
Clearly, the auto-generated binding expression Path=My Col. Name is not valid. The entire path needs to be “quoted” so as to allow spaces and periods. Is there any way to stick with AutoGeneratedColumns for tables with more complex column names, or do I have to go all manual now?
You could try handling
resultsGrid.AutoGeneratingColumns– or more preferably, do this just to the grid before the set gets databound – to replace or remove spaces or periods in the column names. You’d have to do this to both the grid and DataSet, though, so if your data gets edited and saved, this method would likely be far more hassle than it’s worth. The efficiency and feasibility of this depends heavily on your app’s structure and behavior, plus I have not tested it, so take it with a sizable grain of salt.As far as I have found (which admittedly isn’t a terribly broad domain), you’re pretty much stuck with this behavior. I’d suggest submitting a bug to Microsoft; it seems like this would be desirable behavior for
AutoGenerateColumns.