Contents
Introduction
Maybe a lot of people know how it is easy in the .NET environment to extend a base class control to add some behaviors to it.
This is what I have done in this project. Maybe also, everybody has looked one day to add the ability to select a row in a gridview
with another way than adding the awful link "select" in one column of this control. The tip was simple, extend the base class gridview
and add a postback
event on each row when it is created.
But this last tip has one inconvenience of course, if we have some columns which contains some links like in the picture above, if we click on the link, this won't raise correctly. In any case, the postback
event of the row will be executed due to its hierarchical power. Then I had to find a little recursive solution that I want to propose to you.
Solution Assemblies
DataDigest.Business
- DataDigest.DataAccess
--> you don't need it, it's just quite an easy way to work with data
DataDigest.Helper
--> contains a recursive class helper which finds any type of controls in any control
DataDigest.WebControls
--> contains the extender gridview
class. Depends on the helper. This is what you need.
Using the Code
- The recurser class:
namespace DataDigest.Helper
{
public static class Recurser
{
public static Control ContainsControlType(Control control, params Type[] types)
{
foreach (Type type in types)
{
if (control.GetType().Equals(type))
return control;
else
foreach (Control ctrl in control.Controls)
{
Control tmpCtrl = ContainsControlType(ctrl, type);
if (tmpCtrl != null)
return tmpCtrl;
}
}
return null;
}
public static bool ContainsLink(Control control)
{
bool ret = false;
Control ctrl = ContainsControlType(control, typeof(HyperLink),
typeof(LinkButton), typeof(DataBoundLiteralControl));
if (ctrl != null)
{
if (ctrl.GetType().Equals(typeof(DataBoundLiteralControl)))
{
DataBoundLiteralControl dblc = (DataBoundLiteralControl)ctrl;
if (dblc.Text.Contains("href") || dblc.Text.Contains("onclick"))
ret = true;
}
else ret = true;
}
return ret;
}
}
}
- Extend the
gridview
:
namespace DataDigest.WebControls
{
[DefaultProperty("SelectedValue")]
[ToolboxData("<{0}:GridView runat="server"></{0}:GridView>")]
public class GridView : System.Web.UI.WebControls.GridView
{
protected override void OnRowCreated(GridViewRowEventArgs e)
{
base.OnRowCreated(e);
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (TableCell cell in e.Row.Cells)
{
if (!Recurser.ContainsLink(cell))
{
cell.Attributes.Add("onclick",
Page.ClientScript.GetPostBackEventReference(this,
"Select$" + e.Row.RowIndex.ToString()));
cell.Style.Add(HtmlTextWriterStyle.Cursor, "pointer");
cell.Attributes.Add("title", "Select");
}
}
}
}
}
}
- Add the reference of the assembly to your web.config then use the new user control ;)
Points of Interest
- Extending base classes
- How to get a
postback
reference
History
- 10th October, 2006: Initial post