My Technical Notes

Monday, 29 April 2013

Showing or Hiding Links In GridView depending on Row that is Bound to it

To show or hide links in a GridView, we need to tap into the RowDataBound event:


<asp:GridView ID="GridView1" 
              runat="server" 
              OnRowDataBound="GridView1_RowDataBound">
...
</asp:GridView>

In the code behind, we first need to check if the row type is a DataRow (as opposed to a EmptyDataRow), then we can retrieve the item from e.Row.DataItem.

In the case binding a DataTable to the GridView, we can retrieve the item like so:


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
  DataRow row = ((DataRowView)e.Row.DataItem).Row;
  
  var someIntegerData = (int)row["MyField"];
  
  if (someIntegerData >= 100)
  {
   e.Row.FindControl("Edit").Visible = false;
  }
 }
}

In the event of using a EntityDataSource, things are a little more complex because we end up using classes/interfaces which we are not familiar with:


protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.EmptyDataRow)
 {
  var dbObj = (e.Row.DataItem as ICustomTypeDescriptor).GetPropertyOwner(null) as MyEntityType;

  if (dbObj.MyField >= 100)
  {
   e.Row.FindControl("Edit").Visible = false;
  }
 }
}

Notice that in the above code we are casting to an ICustomTypeProvider etc.

No comments: