This is a migrated thread and some comments may be shown as answers.

[Solved] OnClick event for telerik:GridHyperLinkColumn

3 Answers 795 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Anuj
Top achievements
Rank 1
Anuj asked on 13 Mar 2012, 04:43 PM
Following is my grid which has autogenerated column to true. I have created two new columns Add Comments and Add Documents.

I want to capture onClick event for these two hyperlink. How can I do that ?

I have tried with <ItemTemplate> and <asp:Hyperlink> but in that case I am loosing all my auto generated column, Please help


'<telerik:RadGrid ID="gvInvoice" Width="98%" AllowPaging="true" AllowSorting="true" PageSize="100"
                                    runat="server" AutoGenerateColumns="true" CellSpacing="0" GridLines="None" Skin="Office2010Blue"
                                    OnPageIndexChanged="gvInvoice_PageIndexChanged"
                                    OnItemDataBound="gvInvoice_ItemDataBound"
                                    OnSortCommand="gvInvoice_SortCommand" 
                                    ShowFooter="True" Height="100%">
                                    <MasterTableView>
                                        <Columns>
                                          <telerik:GridHyperLinkColumn Text="Add Comments" UniqueName="Comments"  HeaderStyle-Width="120px" HeaderText="Comments" NavigateUrl="#"></telerik:GridHyperLinkColumn>
                                          <telerik:GridHyperLinkColumn Text="Add Documents" UniqueName="Documents" HeaderStyle-Width="120px" HeaderText="Document" NavigateUrl="#"></telerik:GridHyperLinkColumn>
                                        </Columns>
                                    </MasterTableView>
                                   
                                    <PagerStyle Mode="NextPrevAndNumeric" />
                                    <ClientSettings>
                                    <Scrolling AllowScroll="true" SaveScrollPosition="true" UseStaticHeaders="true" /></ClientSettings>
                                </telerik:RadGrid>'


Any suggestion ?

3 Answers, 1 is accepted

Sort by
0
Andrey
Telerik team
answered on 16 Mar 2012, 10:05 AM
Hello,

You could attach and event handler to the LinkButtons in the ItemDataBound event handler of RadGrid. In its body you need to check whether the currently bound item is GridDataItem  and if it is you could find the LinkButtons through this code:

C#
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            GridDataItem dataItem = e.Item as GridDataItem;
            LinkButton addComments = dataItem["Comments"].Controls[0] as LinkButton;
            addComments.Click += new EventHandler(addComments_Click);
            LinkButton AddDocuments = dataItem["Documents"].Controls[0] as LinkButton;
            AddDocuments.Click += new EventHandler(AddDocuments_Click);
        }
    }
 
    protected void AddDocuments_Click(object sender, EventArgs e)
    {
        //put your custom code here...
    }
 
    protected void addComments_Click(object sender, EventArgs e)
    {
        //put your custom code here...
    }

VB.NET

Protected Sub RadGrid1_ItemDataBound(sender As Object, e As GridItemEventArgs)
    If TypeOf e.Item Is GridDataItem Then
        Dim dataItem As GridDataItem = TryCast(e.Item, GridDataItem)
        Dim addComments As LinkButton = TryCast(dataItem("Comments").Controls(0), LinkButton)
        AddHandler addComments.Click, AddressOf addComments_Click
        Dim AddDocuments As LinkButton = TryCast(dataItem("Documents").Controls(0), LinkButton)
        AddHandler AddDocuments.Click, AddressOf ddDocuments_Click
    End If
End Sub
 
Protected Sub AddDocuments_Click(sender As Object, e As EventArgs)
    'put your custom code here...
End Sub
 
Protected Sub addComments_Click(sender As Object, e As EventArgs)
    'put your custom code here...
End Sub

Give this approach a try and let me know if you need further assistance.

All the best,
Andrey
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now.
0
IgorVM
Top achievements
Rank 1
answered on 16 Jul 2013, 05:26 AM
Hello, Andrey!
I tried to use your code, but this doesn't work for me and I don't know why. Can you explain this for me?
I have this RadGrid
telerik:RadGrid  ID="grTransportChanges" runat="server" GridLines="None" AllowFilteringByColumn="true" BorderWidth="0" BorderColor="White"
            AllowPaging="True" Culture="ru-RU" AllowAutomaticInserts="True" AllowAutomaticDeletes="false" AllowAutomaticUpdates="True" AllowMultiRowSelection="true"
            AllowSorting="True" ShowGroupPanel="true" Skin="Office2007"  AutoGenerateColumns="False" PageSize="100"
            EnableHeaderContextMenu="true" EnableHeaderContextFilterMenu="false"       
            Width="100%" Height="100%" GroupPanel-Width="100%" ShowFooter="true" OnItemDataBound="RadGrid_ItemDataBound">
        <GroupingSettings CaseSensitive="false" />       
        <MasterTableView EditMode="PopUp" DataKeyNames="Id" TableLayout="Auto" ClientDataKeyNames="Id" ShowFooter="true">
            <SortExpressions>
            <telerik:GridSortExpression FieldName="Description" SortOrder="Descending" />
            </SortExpressions>
            <Columns>
                <telerik:GridHyperLinkColumn Target="_blank" DataTextField ="Vehicle.Id" HeaderText="Id" UniqueName="Id" SortExpression="Id" AllowFiltering="false"/>               
                <telerik:GridHyperLinkColumn DataTextField ="Vehicle.ModelName" HeaderText="Модель" UniqueName="ModelName" SortExpression="ModelName" ShowFilterIcon="false" AutoPostBackOnFilter="true" FilterControlWidth="95%" CurrentFilterFunction="Contains" DataType="System.String"/>
                <telerik:GridHyperLinkColumn DataNavigateUrlFormatString="~/AddClient.aspx?id={0}" DataNavigateUrlFields="Vehicle.Client.Id" DataTextField ="Vehicle.Client.Name" HeaderText="Владелец" UniqueName="Vehicle.Client.Name" SortExpression="Vehicle.Client.Name" ShowFilterIcon="false" AutoPostBackOnFilter="true" FilterControlWidth="95%" CurrentFilterFunction="Contains" DataType="System.String"/>
                <telerik:GridBoundColumn DataField="Vehicle.PricePerKm" UniqueName="Vehicle.PricePerKm" HeaderText="Цена/км" SortExpression="Vehicle.PricePerKm" ShowFilterIcon="false" AutoPostBackOnFilter="true" FilterControlWidth="95%"/>
                <telerik:GridBoundColumn DataField="Vehicle.MinOrderHours" UniqueName="Vehicle.MinOrderHours" HeaderText="Минимальное время" SortExpression="Vehicle.MinOrderHours" ShowFilterIcon="false" AutoPostBackOnFilter="true" FilterControlWidth="95%"/>
                <telerik:GridBoundColumn DataField="Vehicle.NumPlaces" UniqueName="Vehicle.NumPlaces" HeaderText="Число мест" SortExpression="Vehicle.NumPlaces" ShowFilterIcon="false" AutoPostBackOnFilter="true" FilterControlWidth="95%" />
                <telerik:GridBoundColumn DataField="Vehicle.City" UniqueName="Vehicle.City" HeaderText="Город" SortExpression="Vehicle.City" ShowFilterIcon="false" AutoPostBackOnFilter="true" FilterControlWidth="95%"/>
                <telerik:GridBoundColumn DataField="Vehicle.Client.MainContactName" HeaderText="Имя" SortExpression="Vehicle.Client.MainContactName" UniqueName="Vehicle.Client.MainContactName" CurrentFilterFunction="Contains" ShowFilterIcon="false" AutoPostBackOnFilter="true" FilterControlWidth="95%" />
                <telerik:GridBoundColumn DataField="Vehicle.Client.Cell" HeaderText="Телефон" SortExpression="Vehicle.Client.Cell" UniqueName="Vehicle.Client.Cell" CurrentFilterFunction="Contains" ShowFilterIcon="false" AutoPostBackOnFilter="true" FilterControlWidth="95%" />
                <telerik:GridBoundColumn DataField="Vehicle.Address" UniqueName="Vehicle.Address" HeaderText="Адрес" SortExpression="Vehicle.Address" ShowFilterIcon="false" AutoPostBackOnFilter="true" FilterControlWidth="95%"/>
                <telerik:GridBoundColumn DataField="Vehicle.Number" UniqueName="Vehicle.Number" HeaderText="Номер" SortExpression="Vehicle.Number" ShowFilterIcon="false" AutoPostBackOnFilter="true" FilterControlWidth="95%"/>
                <telerik:GridBoundColumn DataField="Vehicle.PropertyTypeStr" UniqueName="Vehicle.PropertyTypeStr" HeaderText="Тип собственности" SortExpression="Vehicle.PropertyTypeStr" ShowFilterIcon="false" AutoPostBackOnFilter="true" FilterControlWidth="95%"/>
                <telerik:GridBoundColumn DataField="Vehicle.Color" UniqueName="Vehicle.Color" HeaderText="Цвет" SortExpression="Vehicle.Color" ShowFilterIcon="false" AutoPostBackOnFilter="true" FilterControlWidth="95%"/>
                <telerik:GridNumericColumn DataField="Vehicle.NumPhotos" UniqueName="Vehicle.NumPhotos" HeaderText="Число фото" SortExpression="NumPhotos" FilterControlWidth="95%"/>
                <telerik:GridDateTimeColumn DataField="ChangedOn" HeaderText="Время отправления" UniqueName="ChangedOn"
                         SortExpression="ChangedOn" ShowSortIcon="True" DataFormatString="{0:dd.MM.yyyy h:mm}" HeaderStyle-Width="100px" FilterControlWidth="105px"
                         PickerType="DatePicker" EnableTimeIndependentFiltering="true" CurrentFilterFunction="EqualTo"/>
                <telerik:GridBoundColumn DataField="Description" UniqueName="Description" HeaderText="Описание правки" SortExpression="Description"/>
                <telerik:GridBoundColumn DataField="ChangedBy" UniqueName="ChangedBy" HeaderText="Изменил" SortExpression="ChangedBy" ShowFilterIcon="false" AutoPostBackOnFilter="true" FilterControlWidth="95%"/>
            </Columns>           
         </MasterTableView>   
         <ClientSettings AllowColumnsReorder="True" ReorderColumnsOnClient="True" AllowDragToGroup="True">
            <Resizing  AllowColumnResize="true" AllowRowResize="true"/>
            <Selecting AllowRowSelect="true" />
            <ClientEvents OnRowContextMenu="RowContextMenu"></ClientEvents>
            <Scrolling AllowScroll="True" UseStaticHeaders="True"  />
        </ClientSettings>
        <PagerStyle Mode="NextPrevAndNumeric" />
    </telerik:RadGrid>

And i tried to do this in code behind
protected void RadGrid_ItemDataBound(object sender, GridItemEventArgs e)
       {
           if (e.Item is GridDataItem)
           {
var item = (GridDataItem)e.Item;
               var clickId = (LinkButton)item["Id"].Controls[0];
               clickId.Click += new EventHandler(deleteRow);
           }
       }

But i have received a NullReferenceException, because clickId is null. Can you help me with this?
0
Andrey
Telerik team
answered on 16 Jul 2013, 02:09 PM
Hello,

The problem with your code is that the GridHyperLinkColumn is rendering HyperLink control not LinkButton control. HyperLink control does not postback and thus it does not have Click event. If you want to have a client-side click event you could use the approach from this MSDN thread.

If you want to have server-side Click event you should use GridTemplateColumn with LinkButton inside its ItemTemplate or your could use GridButtonColumn with ButtonType set to LinkButton.

Regards,
Andrey
Telerik
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to the blog feed now.
Tags
Grid
Asked by
Anuj
Top achievements
Rank 1
Answers by
Andrey
Telerik team
IgorVM
Top achievements
Rank 1
Share this question
or