C1DataGrid : Print Selected Cell Range
ComponentOne DataGrid for WPF supports printing and has an inbuilt Print method to achieve the same. This blog explains an approach on how one can print the selected range of cells in the C1DataGrid control. We will follow the below mentioned steps to implement the same :
- Create a filtered data table such that it contains only that range of rows & columns, which are selected in the grid.
- Programmatically create a new grid control.
- Bind the dynamically created grid to the filtered data table.
- Print the dynamically created grid.
Basic Grid Setup
To start the implementation, we need to bind the data and set the SelectionMode property. To bind the grid to a datasource, you can refer to here. Select a range of cells by setting the SelectionMode property of the grid to 'MultiRange'. Our grid will look as follows :
Step I) Create Filtered DataTable
private DataTable GetTableOfSelectedRange(C1.WPF.DataGrid.C1DataGrid view)
{
// create a table containing the selection range
DataTable resultTable = new DataTable();
DataTable sourceTable = null;
// create lists for selected row & column ranges
var rowSel = c1DataGrid1.Selection.SelectedRows.ToList();
var colSel = c1DataGrid1.Selection.SelectedColumns.ToList();
if (view.ItemsSource is DataView)
sourceTable = ((DataView)view.ItemsSource).Table;
if (sourceTable != null)
{
for (int colHandle = 0; colHandle < colSel.Count; colHandle++)
{
resultTable.Columns.Add(new DataColumn(colSel[colHandle].Name));
}
for (int rowHandle = 0; rowHandle < rowSel.Count; rowHandle++)
{
ArrayList values = new ArrayList();
for (int colHandle = 0; colHandle < colSel.Count; colHandle++)
{
values.Add(colSel[colHandle].GetCellValue(rowSel[rowHandle]));
}
resultTable.Rows.Add(values.ToArray());
}
resultTable.AcceptChanges();
}
return resultTable;
}
Step II) Create New Grid control in Code
// Create a CloneGrid
C1.WPF.DataGrid.C1DataGrid clonedGrid = new C1DataGrid();
// Add it to the Visual Tree
grid1.Children.Add(clonedGrid);
Step III) Bind Grid to Filtered DataTable
// Assign the cloneTable as the Itemsource for the cloneGrid
DataTable clonedTable = GetTableOfSelectedRange(c1DataGrid1);
clonedGrid.ItemsSource = clonedTable.AsDataView();
Step IV) Print Grid (Selected Range)
//Print the Grid
clonedGrid.Print("test");
Refer to the below image that depicts the generated output : Download Sample CS Download Sample VB