The DataGridTableStyle is a class that represents how the datagrid to be displayed. Through,the DataGridTableStyle you can control the appearance of the grid for each DataTable to be displayed in the datagrid. DataGridTableStyle has properties called mapping name ,to which datatable name is given for which tablestyle is to be applied.
Let us assume there is table named “Details” with the fields “Names”,”Address”. And also there is other table called “Customer Details” with fields “Names”,”PurchaseAmount". The following article will show you how to define different DataGridTableStyles for the above tables
/* Create a new DataGridTableStyle and set its MappingName to the TableName of a DataTable
"Details" and also we can set properties like PreferredRowWidth,alternating background color */
DataGridTableStyle objDGTStyle=new DataGridTableStyle();
objDGTStyle.MappingName="Details";
objDGTStyle.PreferredRowHeight=30;
objDGTStyle.RowHeadersVisible=true;
objDGTStyle.AlternatingBackColor=Color.LightGray;
objDGTStyle.SelectionBackColor=Color.Navy;
We had mapped the "Details" table to DataGridTableStyle,now we have to map each column of the datatable to DataGridTextBoxColumn beacause each column of the datagrid is made of TextBox.We can change the width,headertext of it.After mapping we are adding it to GridColumnStylesCollection of DataGridTableStyle.Finally we are adding it to datagrid
/*Add a GridColumnStyle and set its MappingName to the name of a DataColumn in the DataTable . Set the HeaderText(text to be displayed) and Width properties.*/
DataGridTextBoxColumn dgtbc=new DataGridTextBoxColumn();
dgtbc.MappingName="Names";
dgtbc.HeaderText="Name";
dgts.GridColumnStyles.Add(dgtbc);
dgtbc=new DataGridTextBoxColumn();
dgtbc.MappingName="Addresses";
dgtbc.HeaderText="Address";
dgtbc.Width=100;
dgts.GridColumnStyles.Add(dgtbc);
/*Create a new DataGridTableStyle and set its MappingName to the TableName of a DataTable
"Customer Details" */
DataGridTableStyle objDGTStyle1=new DataGridTableStyle();
ObjDGTStyle1.MappingName="Customer Details";
ObjDGTStyle1.PreferredRowHeight=30;
ObjDGTStyle1.AlternatingBackColor=Color.LightGray;
ObjDGTStyle1.SelectionBackColor=Color.Pink;
//Similarly add a gridcolumn style to columns of “Customer Details” table.
//Adding datagridtablestyle to datagrid.
DataGrid1.TableStyles.Add(objDGTStyle);
DataGrid1.TableStyles.Add(objDGTStyle1);
When "Details" table is binded to datagrid it displays style objDGTStyle.When "Customer Details" table is binded to datagrid.it displays style objDGTSyle1.