Changing
Column Properties Programmatically
You can easily set the properties for DataGrid column
during design mode. But if you want to set it programatically, then you
need to follow a different way. In most cases you want to set the column
properties like width or visible based on certain conditions. In that case
you need to do it programmatically only. In this code snippet,i am going
to explain this. For setting column properties programatically, you need
to use itemstyle property of datagrid column.
Setting
Width of a column
Here is the code snippet for setting column property.
In this example, i am setting width for the second column in a
datagrid.
datagrid1.Columns(0).ItemStyle.Width.Pixel(150)
or
datagrid1.Columns(0).ItemStyle.Width = new Unit(150,UnitType.Pixel)
For
setting width property, you need to use unit structure. In this
example i used pixel unit type, but you can also use other unit types like
percentage, point and parse. You can set the width in Page_Load event
handler.
Showing and hiding columns(Setting visible property)
One way to have columns appear dynamically is to create them at design time, and
then to hide or show them as needed. You can do this by setting a column's
Visible property. The following example shows how to toggle the visibility of
the second column of the DataGrid.
DataGrid1.Columns(1).Visible = Not (DataGrid1.Columns(1).Visible)
Aligning DataGrid column
For aligning datagrid column text dynamically, you can use the same
itemstyle property of DataGrid Column. For example to align the text in
center(horizontally),
DataGrid1.Columns(0).ItemStyle.HorizontalAlign=HorizontalAlign.Center
You need to use HorizontalAlign or VerticalAlign property of itemstyle property
to align text inside any columns in DataGrid.
|