I have a grid that needs to hide certain columns right after its data-bound. Here’s my code so far:
private IEnumerable<DataGridColumn> GetDataGridColumns(DataGrid grid)
{
var itemsSource = grid.ItemsSource as IEnumerable;
if (null == itemsSource) yield return null;
foreach (var item in itemsSource)
{
var column = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridColumn;
if (null != column) yield return column;
}
}
private void LoadData()
{
GridMain.ItemsSource = (new VTAEEntities()).OrganizationInterfaces.ToList();
foreach (DataGridColumn Column in GetDataGridColumns(GridMain))
{
// Hiding columns
if (Column.Header as String != null) {
String tempHeader = Column.Header as String;
String[] unrequiredColumns = new String[] {
"Instances",
"Interfaces",
"Organizations",
"RegisteredCallerOnly"
};
if (unrequiredColumns.Contains(tempHeader)) {
Column.Visibility = System.Windows.Visibility.Hidden;
}
}
// Read-only columns
if (Column.Header as String != null)
{
String tempHeader = Column.Header as String;
String[] unrequiredColumns = new String[] {
"InstanceId",
"InterfaceId",
"OrganizationId"
};
if (unrequiredColumns.Contains(tempHeader))
{
Column.IsReadOnly = true;
}
}
}
}
All the unwanted columns + the columns I want to be read only are all there. Upon debugging, I realize that the GridMain.Columns is always 0 count. How do I iterate through the columns in an ItemSource?
If you want to hide column than you can make use of
event of wpf grid that will might work for you to hide column.