Introduction
When converting DataTable
s to GridView
controls in large (intranet), object reference errors often occur when a BoundColumn
is set to "Visible=false
".
Background
In applications that use the DataTable
control, BoundColumn
s are sometimes set to invisible when a developer wants to hide data from users while using hidden data in client-side applications such as JavaScript.
The BoundField
however, doesn't render any data on the client side when "visible" is set to false
. When converting large applications, this might cause some problems. The normal fix would be to set the "visible
" property programmatically to false
after the "OnDataBind
" event. However, this solution costs time.
To solve this problem in a short time span, I made my own class that uses BoundField
as its base. The class simply solves the issue by setting the value of the field to visible on init, and restoring it after the field is bound.
Using the Code
To use this solution, place a new class in your app code called BoundColumnField
. Add the following code to that class:
namespace GridViewFix
{
public class BoundColumnField : BoundField
{
private Boolean NotVisible;
protected override void InitializeDataCell(
DataControlFieldCell cell, DataControlRowState rowState)
{
NotVisible = false;
if (!this.Visible)
{
this.Visible = true;
NotVisible = true;
}
base.InitializeDataCell(cell, rowState);
}
protected override void OnDataBindField(object sender, EventArgs e)
{
base.OnDataBindField(sender, e);
if (NotVisible) this.Visible = false;
}
}
}
First register your namespace on the top of each page where you want to use this control, as follows:
<%@ Register TagPrefix="GridViewFix" Namespace="GridViewFix"%>
Next, you can use the class in your DataGrid
s (using <GridViewFix:BoundColumnField>
instead). The usage of the class is the same as that of the BoundField
class. Only the render behavior is compatible with the old BoundColumn
control.
Points of Interest
Microsoft removed the rendering of invisible fields for security reasons. This fix changes the behavoir of hidden fields. Please keep in mind that hidden values will be accessible to users when they open the client-side code.
History
- 1.0: Added my first article here - 06 September 2007.