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

Gridview cell click event

22 Answers 1295 Views
GridView
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
NickZ
Top achievements
Rank 1
NickZ asked on 29 Apr 2009, 09:57 PM
Hello, is there a cell click event for Rad Gridview?  I try to open a new window by clicking on a specific gridview cell.  The new window will display information based on that cell's value.  Thanks.

22 Answers, 1 is accepted

Sort by
0
Pavel Pavlov
Telerik team
answered on 04 May 2009, 01:35 PM
Hello NickZ,

There is no such event available but there is an easy way to gain such behavior:

1. First we put a clickable UIElement in our cell ( in our case a border )  by redefining the cell template :
2. Hook up the MouseLeftButtonDown event  of that element in XAML .


Here is some sample XAML :
...  
    <Grid x:Name="LayoutRoot" Background="White">  
        <Grid.Resources> 
            <DataTemplate x:Key="clickableCellTemplate">  
                <Border MouseLeftButtonDown="Border_MouseLeftButtonDown" Width="50" Height="50" Background="Red" /> 
            </DataTemplate> 
        </Grid.Resources> 
        <telerik:RadGridView x:Name="RadGridView1" AutoGenerateColumns="False" > 
            <telerik:RadGridView.Columns> 
                <telerik:GridViewDataColumn  CellTemplate="{StaticResource clickableCellTemplate}"  /> 
            </telerik:RadGridView.Columns> 
        </telerik:RadGridView> 
    </Grid> 
</UserControl> 

3. Perform our action (e.g. open a new window ) within the event handler in code behind.
private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)  
        {  
             //Place your custom code to open a window here.
        }  
 

Note : To find out which cell was clicked you may need to bind the column to some data(in our case it is unbound) . Then within the eventhandler you may check the datacontext.

Kind regards,
Pavel Pavlov
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
0
NickZ
Top achievements
Rank 1
answered on 04 May 2009, 06:19 PM
Hi Pavel, thanks for your help.

I tested your code and got the following exception:
throw new Error("Unhandled Error in Silverlight 2 Application AG_E_PARSER_PROPERTY_NOT_FOUND [Line: 55 Position: 82] at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)\n at RoadCare3Simulations.Simulation.InitializeComponent()\n at RoadCare3Simulations.Simulation..ctor()\n at RoadCare3Simulations.App.Application_Startup(Object sender, StartupEventArgs e)\n at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)\n at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)");
It seems that 'CellTemplate' doesn't exist, because I don't see it in intellisense window.

In my case, this gridview is actually located inside a RadPane, and content is added by code.

<radDock:RadPane x:Name="Pane03" Header="MyTab" Title="MyTab"> <radDock:RadPane.Content>

 

 

 

<radGrid:RadGridView

 

 

x:Name="radGridViewDataBinding"

 

 

ScrollMode="RealTime" ColumnsWidthMode="Auto"

 

 

AutoGenerateColumns="False" >

 

 

 

<radGrid:RadGridView.Columns>

 

 

 

<radGrid:GridViewDataColumn CellTemplate="{StaticResource clickableCellTemplate}" />

 

 

 

</radGrid:RadGridView.Columns>

 

 

 

</radGrid:RadGridView>

 

 

 

</radDock:RadPane.Content>

 

 

 


Could you please give me some code sample for this cell click?  How can I get the cell location info (column and row)? Thanks a lot.

 

 

 

0
BlogReader
Top achievements
Rank 1
answered on 04 May 2009, 11:47 PM
Hey Nickz,
What I do is that I subscribe to the RowLoaded event of the grid. In the event handler I access the required cells of the row and I subscribe to the GridViewCellBase.MouseLeftButtonDown (Line 7) event. I am listing some sample code below:

        private void Grid_RowLoaded(object sender, RowLoadedEventArgs e) 
        { 
            if (e.Row is GridViewRow && !(e.Row is GridViewNewRow) && !(e.Row is GridViewExpandableRow)) 
            { 
                foreach (GridViewCellBase cell in e.Row.Cells) 
                { 
                      cell.MouseLeftButtonDown += Grid_CellMouseLeftButtonDown; 
                      cell.Cursor = Cursors.Hand; 
                } 
 
            } 
        } 


0
Pavel Pavlov
Telerik team
answered on 05 May 2009, 02:41 PM
Hi Arjun ,

I am not sure this is a good approach .
The RowLoaded event is fired anytime the row appears within the viewport.  I don't see a place in your code to unsubscribe from the event. This Means when you scroll /sort/group or perform another operations you always resubscribe for the event. as a result you may get memory  and performance problems as well as unexpected behavior for example multiple invocations of the event handler for a single row. 
Generally I would not recommend to subscribe to another events in the RowLoaded event.


I am preparing a sample project and will post it in this thread soon .



All the best,
Pavel Pavlov
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
0
BlogReader
Top achievements
Rank 1
answered on 05 May 2009, 03:08 PM
Ok. That makes sense. I will try the approach that you have suggested in your earlier reply. 

However I do have this question: What happens when the grid's ItemSource property is set to a empty list? Is the destructor called on all the GridViewCellBase objects? Will the garbage collector free up the memory? 
0
Pavel Pavlov
Telerik team
answered on 08 May 2009, 02:39 PM
Hi all,

As promised I am attaching a sample project  demonstrating a possible way of handling mouse clicks via user control placed in the Cell's  datatemplate. Please excuse me for the delay.

Sincerely yours,
Pavel Pavlov
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
0
NickZ
Top achievements
Rank 1
answered on 08 May 2009, 08:52 PM
Hi Pavel,
Thanks for the code and it works perfectly.  But in my case, my gridview is created dynamically.  Can you give me some sample codes about how to create those mouse button down events on a programmtically created gridview cell? 
Thanks again.
0
Pavel Pavlov
Telerik team
answered on 11 May 2009, 12:47 PM
Hello NickZ,

Since I 'am not sure what do you mean by  "programmtically created gridview cell" , can you please send me some source (ideally a whole project) and I will try to modify it for you to handle cell clicks.

Kind regards,
Pavel Pavlov
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
0
NickZ
Top achievements
Rank 1
answered on 11 May 2009, 09:55 PM
Hi Pavel,

Sorry that I didn't explain it cleary.  Please see my other posts at SilverLight:DockPanel:  http://www.telerik.com/community/forums/silverlight/dockpanel/add-a-new-dockpanel-programmically.aspx

Basically, I want to creat a dockable panel by clicking a button or selecting a node on treeview.  The content of panel is a gridview.  That is what I said that gridview is created programmtically.  I am looking for the cell click event inside that gridview. 

Thanks a lot.
0
Pavel Pavlov
Telerik team
answered on 15 May 2009, 03:38 PM
Hello NickZ,
The attached example shows  a way to have clickable cells in a RadGridView in a DockPanel. It combines both examples mine and the one from your thread.
Hope it fits your scenario.

Regards,
Pavel Pavlov
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
0
NickZ
Top achievements
Rank 1
answered on 19 May 2009, 01:40 PM
Thanks, Pavel.  The code sample is very helpful.
0
NickZ
Top achievements
Rank 1
answered on 19 May 2009, 01:40 PM
Thanks, Pavel.  The code sample is very helpful.
0
NickZ
Top achievements
Rank 1
answered on 01 Jun 2009, 09:52 PM
Hi Pavel,

I added your code to my project, but I always got error of "in Silverlight 2 Application AG_E_PARSER_PROPERTY_NOT_FOUND".  I ran your code and it works perfectly.  It is weird since I didn't see much difference between yours and mine.  Could you please help me on this?  I attach my codes here. 

<UserControl x:Class="RoadcareSimulationResults.Page" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"   
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"   
    xmlns:Controls="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Docking"   
    xmlns:telerikDocking="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Docking" 
    xmlns:telerikNavigation="clr-namespace:Telerik.Windows.Controls;assembly=Telerik.Windows.Controls.Navigation"   
    Width="1050">  
    <Grid x:Name="LayoutRoot" Background="AliceBlue">  
        <Grid.RowDefinitions> 
            <RowDefinition Height="10" /> 
            <!--0 Margin--> 
            <RowDefinition Height="*" /> 
            <!--2 DataGrid--> 
            <RowDefinition Height="10" /> 
            <!--3 Margin--> 
        </Grid.RowDefinitions> 
        <Grid.ColumnDefinitions> 
            <ColumnDefinition Width="20" /> 
            <!--0 Margin--> 
            <ColumnDefinition Width="*" /> 
            <!--1 Controls--> 
            <ColumnDefinition Width="80" /> 
            <!--2 Margin--> 
        </Grid.ColumnDefinitions> 
 
        <telerikDocking:RadDocking x:Name="radDocking1" Grid.Row="1" Grid.Column="1">  
            <telerikDocking:RadDocking.DocumentHost> 
                <Controls:RadSplitContainer> 
                    <Controls:RadPaneGroup x:Name="radPaneGroup1" /> 
                </Controls:RadSplitContainer> 
            </telerikDocking:RadDocking.DocumentHost> 
              
            <telerikDocking:RadSplitContainer telerikDocking:DockingPanel.InitialSize="200,200" 
                    x:Name="BottomContainer" InitialPosition="DockedBottom">  
                <telerikDocking:RadPaneGroup x:Name="Group3">  
                    <telerikDocking:RadPane x:Name="Pane05" Header="Output">  
                        <telerikDocking:RadPane.Content> 
                            <TextBlock TextWrapping="Wrap">  
                                <TextBlock.Text> 
                                    This is a good one.  
                                </TextBlock.Text> 
                            </TextBlock> 
                        </telerikDocking:RadPane.Content> 
                    </telerikDocking:RadPane> 
                </telerikDocking:RadPaneGroup> 
            </telerikDocking:RadSplitContainer> 
              
            <telerikDocking:RadSplitContainer telerikDocking:DockingPanel.InitialSize="200,150" MaxWidth="600" 
                x:Name="LeftContainer" InitialPosition="DockedLeft">  
                <telerikDocking:RadPaneGroup x:Name="Group1">  
                    <telerikDocking:RadPane x:Name="Pane04" Header="Tree View">  
                    </telerikDocking:RadPane> 
                </telerikDocking:RadPaneGroup> 
            </telerikDocking:RadSplitContainer> 
 
        </telerikDocking:RadDocking> 
    </Grid> 
</UserControl> 
using System.Collections;  
using System.Collections.ObjectModel;  
using System.Windows;  
using System.Windows.Controls;  
using System.Windows.Media;  
using Telerik.Windows.Controls;  
using Telerik.Windows.Input;  
using Telerik.Windows;  
using System;  
using Telerik.Windows.Controls.Docking;  
 
 
namespace RoadcareSimulationResults  
{  
    public partial class Page : UserControl  
    {  
        public Page()  
        {  
            InitializeComponent();  
            this.Loaded += this.Page_Loaded;  
        }  
 
        void Page_Loaded(object sender, RoutedEventArgs e)  
        {  
            RadPane panelWithGrid = this.CreatePanelWithGrid();  
            this.radPaneGroup1.AddItem(panelWithGrid, DockPosition.Right);  
        }  
 
        private RadPane CreatePanelWithGrid()  
        {  
            RadPane panel = new RadPane();  
            panel.Header = "My Header";  
            panel.Title = "My Title";  
 
            GridHolder holder = new GridHolder();  
            holder.RadGridView.ItemsSource = new[] { "one", "two", "three" };  
 
            panel.Content = holder;  
            return panel;  
        }  
    }  
}  
 
Thanks a lot for your help. 
0
alan
Top achievements
Rank 1
answered on 03 Jun 2009, 03:13 PM
This seems a rather verbose way of acheiving something that would be very straightforward in any other grid I've used. All I would like is a RowClick and CellClick event that is available in the codebehind of the grid's parent page, this is such a common requirement, why is it not available, is this a Silverlight issue? 

Also how do you change row color and selected row color dynamically in c#? I have changed the cell backcolor but it seems to stop the selected color and the row mouseover colors from showing.

Thanks Alan.
0
Pavel Pavlov
Telerik team
answered on 04 Jun 2009, 01:35 PM

Hello Alan,

We are working on improvements of the RadGridView API for our next release. These will include a more intuitive way of handling cell clicks.

Regarding your other question : The background color of the GridViewRow could be set using the RadGridView.RowStyle property.

Sincerely yours,

Pavel Pavlov
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Check out the tips for optimizing your support resource searches.
0
Thomas LEBRUN
Top achievements
Rank 1
answered on 01 Sep 2009, 10:23 PM
Hi Pavel,

Do you have any news for handling cell click on RadGridView ? In my case, I need to manage cell mouse double click: every time a cell is double clicked, I need to be able (mayble with the args) to find the cell that is clicked.

Any ideas on how I could implement this ?



Thanks !
0
Pavel Pavlov
Telerik team
answered on 07 Sep 2009, 08:09 AM

Hi Thomas ,

With the current version of the grid the recommended approach is to place your own UIElement within the cell (by modifying the cell template) and handle its mouse events.

For the upcoming new official version we have added new mouse events to RadGridview which will make such task as trivial as it should be. These events will carry info about the cell and the related row, column and relevant data object.
If you need the new API urgently  , please check the upcoming internal build ( next Friday) . I believe the new events will be included .

Best wishes,

Pavel Pavlov
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
0
Clint Singer
Top achievements
Rank 1
answered on 24 Sep 2009, 08:31 PM
Did the new mouse events miss the internal build?  I am running 3_0916 which may have been the next internal build (depending on your definition of next Friday.)

Perhaps there is a newer internal build but I can't see it as I am currently evaluating the product as a trial user?

Additionally it would be nice if you could please elaborate on what the changes are or will be.

Cheers
0
Pavel Pavlov
Telerik team
answered on 25 Sep 2009, 11:21 AM
Hello Clint ,

Please have a look at the attached sample. It demonstrates a way to handle mouse clicks on cells.
I hope this could easily fit to your scenario.

Best wishes,
Pavel Pavlov
the Telerik team

Instantly find answers to your questions on the new Telerik Support Portal.
Watch a video on how to optimize your support resource searches and check out more tips on the blogs.
0
Aurélien Dubosson
Top achievements
Rank 1
answered on 27 May 2010, 02:14 PM
Hi everyone,

I just a problem to obtain the row index when I click in a cell. 
I can obtain the column index with that : 

 private void MouseDownOnCell(object sender, MouseButtonEventArgs e)
        {
        
            var colIndex = ((UIElement) e.OriginalSource).ParentOfType<GridViewCell>().Column.DisplayIndex;
}

but I don't know how to get the row index ?


0
Vlad
Telerik team
answered on 27 May 2010, 02:21 PM
Hello,

Here is an example:

var cell =((UIElement) e.OriginalSource).ParentOfType<GridViewCell>();
var rowIndex = cell.Column.DataControl.Items.IndexOf(cell.DataContext);

Greetings,
Vlad
the Telerik team

Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items.
0
Manuel
Top achievements
Rank 1
answered on 22 Jun 2012, 08:39 AM

this is a example of a Behavior to handle a double click in a cell, you can modify to add the right & left mouse clicks!

using System;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.ComponentModel;
using System.Windows.Interactivity;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;

namespace CellDoubleClickExample
{
/// <summary>
/// Behavior that fires a event or command when a DoubleClick in a cell
/// </summary>
public class CellDoubleClickBehavior : Behavior<GridViewBoundColumnBase>
{
/// <summary>
/// Event to Handle when has Double Click
/// </summary>
public event EventHandler<CellEventArgs> CellDoubleClick;
#region Properties
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register(
"Command", typeof(ICommand),
typeof(CellDoubleClickBehavior), new PropertyMetadata(null)
);
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.Register(
"CommandParameter", typeof(object),
typeof(CellDoubleClickBehavior), new PropertyMetadata(null)
);
/// <summary>
/// Command to Handle de DoubleClick
/// </summary>
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
/// <summary>
/// Command Argument to Handle in the command
/// </summary>
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
#endregion
#region Handled Events
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.PropertyChanged += new PropertyChangedEventHandler(AssociatedObject_PropertyChanged);
this.AssociatedObject_PropertyChanged(this, new PropertyChangedEventArgs("DataControl"));
}
void AssociatedObject_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName.Equals("DataControl", StringComparison.InvariantCultureIgnoreCase))
{
if (this.AssociatedObject.DataControl != null)
{
this.AssociatedObject.DataControl.CellLoaded -= CellClickBehavior_CellLoaded;
this.AssociatedObject.DataControl.CellLoaded += CellClickBehavior_CellLoaded;
        this
.AssociatedObject.DataControl.CellUnloaded -= DataControl_CellUnloaded;
        this.AssociatedObject.DataControl.CellUnloaded += DataControl_CellUnloaded;
}
}
}
void CellClickBehavior_CellLoaded(object sender, Telerik.Windows.Controls.GridView.CellEventArgs e)
{
if (object.ReferenceEquals(e.Cell.DataColumn, this.AssociatedObject))
    {

          e.Cell.CellDoubleClick -= Cell_CellDoubleClick;

    e.Cell.CellDoubleClick += Cell_CellDoubleClick;
}
}
void DataControl_CellUnloaded(object sender, Telerik.Windows.Controls.GridView.CellEventArgs e)
{
if (object.ReferenceEquals(e.Cell.DataColumn, this.AssociatedObject))
{
e.Cell.CellDoubleClick -= Cell_CellDoubleClick;
}
}
void Cell_CellDoubleClick(object sender, Telerik.Windows.RadRoutedEventArgs e)
{
if (Command != null && Command.CanExecute(CommandParameter)) Command.Execute(CommandParameter);
if (CellDoubleClick != null) CellDoubleClick(this, new CellEventArgs((GridViewCellBase)sender));
}
#endregion
}
}

easy use in silverlight:

        <telerik:RadGridView x:Name="RadGridView2" IsReadOnly="True" AutoGenerateColumns="False">
            <telerik:RadGridView.Columns>
                <telerik:GridViewDataColumn DataMemberBinding="{Binding Key}" Header="Clave">
                    <i:Interaction.Behaviors>
                        <local:CellDoubleClickBehavior CellDoubleClick="CellDoubleClickBehavior_CellDoubleClick" />
                    </i:Interaction.Behaviors>
                </telerik:GridViewDataColumn>
                <telerik:GridViewDataColumn DataMemberBinding="{Binding Value}" Header="Valor" />
            </telerik:RadGridView.Columns>
        </telerik:RadGridView>

And in code behind:

private void CellDoubleClickBehavior_CellDoubleClick(object sender, Telerik.Windows.Controls.GridView.CellEventArgs e)
{
    MessageBox.Show("Ok " + ((Telerik.Windows.Controls.GridView.GridViewCell)e.Cell).Value.ToString());
}

That's all folks, bye!

 

Tags
GridView
Asked by
NickZ
Top achievements
Rank 1
Answers by
Pavel Pavlov
Telerik team
NickZ
Top achievements
Rank 1
BlogReader
Top achievements
Rank 1
alan
Top achievements
Rank 1
Thomas LEBRUN
Top achievements
Rank 1
Clint Singer
Top achievements
Rank 1
Aurélien Dubosson
Top achievements
Rank 1
Vlad
Telerik team
Manuel
Top achievements
Rank 1
Share this question
or