Row Highlighting Data Control Field
The gridview and detailsview controls, which support using DataControlField classes for their columns, support the addition of any DataControlField custom fields you create. For instance, I created a RowField custom field that is hidden, but highlights the row in the gridview row. Below is the class I created:
public class RowField : DataControlField
{
//Don't allow the visible property to be set
new public bool Visible
{
get { return false; }
set { }
}
protected override DataControlField CreateField()
{
return new RowField();
}
public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
{
base.InitializeCell(cell, cellType, rowState, rowIndex);
//Hide the cell so it isn't visible
base.Visible = false;
//Hook into the data binding
if (cellType == DataControlCellType.DataCell)
cell.DataBinding += new EventHandler(cell_DataBinding);
}
void cell_DataBinding(object sender, EventArgs e)
{
Control control = sender as Control;
//The Row is available in data binding stage, but not initialization
GridViewRow row = control.NamingContainer as GridViewRow;
//Add coloring attributes
row.Attributes.Add("onmouseover", "this.bgColor = '#C0C0C0'");
row.Attributes.Add("onmouseout", "this.bgColor = '#FFFFFF'");
}
}
When you inherit from it, it creates the CreateField by default, which is declared abstract/mustoverride in the base class. This class creates a new instance of the field. The other method I overridden was the InitializeCell class, which initializes the cell by adding controls based on the state of the row, or binding the value in the field. I also make sure that the control isn't visible, as it doesn't hold a value.
In this instance, I wanted to add custom code to color the row whenever it was moused over, or unselect it whenever mouse out occurred. But, to do this, you have to color the row. The row isn't accessible until binding, not during initialization. So I had to tap into the DataBinding event, which has access to the parent naming container (the GridViewRow), and so I could append attributes to.
This seems like overkill though; why not just tap into the itemdatabound or itemcreated event? Well, this serves as an introduction to the class, but it will be useful for another control that I will be creating, hopefully that I will be posting about.
Comments