How to add “ClientSide Click Event” to “ASPxHyperLink” dynamically (as ASPxGridView Data Item Template Control)


As I described above, we can use “OnInit” methots to define dynamic behaviours for any control.

You can just check this article for further information.

And the back-end code;

protected void dxHyperLink_Init(object sender, EventArgs e)
        {
            ASPxHyperLink link = sender as ASPxHyperLink;
            string param = Request.QueryString["param"];

            if (!string.IsNullOrEmpty(param))
            {
                GridViewDataItemTemplateContainer container = link.NamingContainer as GridViewDataItemTemplateContainer;

                WebDescriptorRowBase webDataRow = null; // WebDescriptorRowBase: Super class of WebDataRow and WebCachedDataRow

                if (container.DataItem.GetType().Equals(typeof(WebDataRow)))
                {
                    webDataRow = container.DataItem as WebDataRow;
                }
                else if (container.DataItem.GetType().Equals(typeof(WebCachedDataRow)))
                {
                    webDataRow = container.DataItem as WebCachedDataRow;
                }

                if (webDataRow != null)
                {
                    string value = webDataRow["value"].ToString(); // Reaching the data which is stored in datasource of the gridview
                    if(param == "option1")
                       link.NavigateUrl = "/option1.aspx?val=" + value;
                    else if(param == "option2")
                       link.NavigateUrl = "/option2.aspx?val=" + value;
                    else
                       link.NavigateUrl = "/errorpage.aspx";
                }
            }
        }

So we can basically call various functions from any DevExpress control with this usage.

Notes:

  • You can reach gridView selected row data over Container.DataItem.
  • DataItem can be represents in two ways depends on the caching settings. If you set the gridview to keep data on cache, you need to use WebCachedDataRow sometimes. So you have to check it every single time. That’s why I use a super class of WebCachedDataRow and WebDataRow. In this way, you can find correct object type easily.
  • And one last note for developers; prevent to use Database Connections in any methots of repeatable controls. Especially for the controls which defined in data item templates of lists or gridviews. These kind of usages will decrease performance dramatically.

-end-