Google
Web Netomatix

How to determine row and cell Index of mouse click inside Silverlight DataGrid?

by Admin 16. March 2010 06:31

Download Sample Projects (116.00 kb)

Some back I wrote about How to customize display of columns in DataGrid in silverlight application. But this customization was limited to accessing DataGridRow and changing of style as a whole. Recently I have come across lot of questions about knowing what row and what cell was accessed by user and other related questions. So this post is about addressing some of the following questions.

  • How to find row and cell index of user selection in DataGrid?
  • How to find row and column index of mouse click in Silverlight datagrid?
  • How to find row and column index of datagrid depending on mouse click?

I thought this was going to be a stright forward excercise. I was expecting some kind of direct method or property on some event that I could access to answer the question. It turned out that half of this question could be answered directly by using GetIndex method on DataGridRow object. But I could not get direct answer to index of cell that a user selected in datagrid. A lot of answers that I found revolved around adding a event handler for mouse events in the template for a given DataGridColumn. That meant that I will have to attach these event handlers to all the columns. Then the question was what if I added the columns dynamically or some other custom implementation.

Coming from classic Win32 and MFC background, I thought there has to be some kind of API that I could use where I could capture moust position and do some kind of hit test to find out location of mouse click or mouse move position. After digging around the APIs, I found VisualTreeHelper class that gave me what I was looking for. Following code snippet shows how I was able to get the column and row index inside DataGrid where moust position was.


private void GetGridRowColumnIndex(Point pt, DataGrid grid, out int rowIndex, out int colIndex, out object dataContext)
{
 rowIndex = -1;
 colIndex = -1;
 dataContext = null;
 var elements = VisualTreeHelper.FindElementsInHostCoordinates(pt, grid);
 if (null == elements ||
	elements.Count() == 0)
 { 
  return;
 }

 // Get the rows and columns.
 var rowQuery = from gridRow in elements where gridRow is DataGridRow select gridRow as DataGridRow;
 var cellQuery = from gridCell in elements where gridCell is DataGridCell select gridCell as DataGridCell;
 var cells = cellQuery.ToList<DataGridCell>();
 if (cells.Count == 0)
 {
  return;
 }
			
 foreach (var row in rowQuery)
 {
  dataContext = row.DataContext;
  rowIndex = row.GetIndex();
  foreach (DataGridColumn col in grid.Columns)
  {
   var colContent = col.GetCellContent(row);
   var parent = GetParent(colContent, typeof(DataGridCell));
   if (parent != null)
   {
    var thisCell = (DataGridCell)parent;
    if (object.ReferenceEquals(thisCell, cells[0]))
    {
     colIndex = col.DisplayIndex;
    }
   }
  }
 }
}

private void ProductsGrid_MouseMove(object sender, MouseEventArgs e)
{
 int rowIndex, colIndex;
 object dataContext;
 GetGridRowColumnIndex(e.GetPosition(null), ProductsGrid, out rowIndex, 
   out colIndex, out dataContext);
 SelectedRow.Text = string.Format("[Page={0}], [Row={1}] ", ProductsPager.PageIndex, rowIndex);
 SelectedColumn.Text = string.Format(" [Cell={0}] ", colIndex);
 if (null != dataContext)
 {
  var prod = dataContext as Product;
  ProductInfo.Text = string.Format("[{0}, {1}] ", prod.Name, prod.Color);
 }
}

You can download the attached project to see the whole code in action. The implementation is in Home.xaml/cs

Views: 1898

Tags: ,

DataGrid | Silverlight

Comments

4/20/2010 1:35:14 AM #

ajax ebook

Thanks for posting the samples, It has helped me a lot with learning silverlight data grid. I read many ebooks for the same.

ajax ebook United States

5/25/2010 12:45:45 AM #

notebook battery manufacturer

find out location of mouse click or mouse move position. After digging around the APIs, I found VisualTreeHelper class that gave me what

notebook battery manufacturer Oman

6/4/2010 5:54:47 PM #

fire equipment



Wish I have the luxury of time to consider using the benefits these site can offer.....

fire equipment United States

6/6/2010 12:15:18 AM #

Michael Majid Toronto

One can enjoy a wood fire worthily only when he warms his thoughts by it as well as his hands and feet. ~Odell Shepherd

Michael Majid Toronto Canada

6/8/2010 10:17:08 AM #

new mexico personal injury attorneys

This blog is truly a gold mine. I have been wallowing on this for quite sometime and here I am reading about it! I will actually try these tips and let you know how they work out! Thanks again mate.

new mexico personal injury attorneys United States

6/10/2010 4:11:33 AM #

Phone Systems for Small Office

his post has been updated to work with the RTW version of the Silverlight 2 DataGrid

Phone Systems for Small Office United States

6/11/2010 10:02:33 PM #

canadian pharmacy

Good detections shared. Me and my friend were arguing about an issue similar to this! Now I know that I was right. lol! Thanks for the information you post.

canadian pharmacy United States

6/13/2010 9:48:14 PM #

ngan hang

Good post, thank you for sharing. Keep up posting.

ngan hang Vietnam

6/15/2010 4:37:22 AM #

Primo Vacations Club

I’ve been looking at your blog for a month or so and have plucked up a heap of sound information as well as enjoyed the way you’ve structured your site.

Primo Vacations Club United States

6/15/2010 11:51:16 PM #

YourNetBiz Scam

wish I had found this blog before today. The advices in this posts are very helpful and I surely will read the other posts of this series too.Thank you for posting this. Your Blog is Bookmarked

YourNetBiz Scam United States

6/18/2010 4:39:22 AM #

Electric Gates Sheffield

many concepts found on the silverlight today really seen very interesting concepts over it. I found revolved around adding a event handler for mouse events in the template for a given DataGridColumn. That meant that I will have to attach these event handlers to all the columns.

Electric Gates Sheffield United States

6/24/2010 12:47:12 AM #

Leslie Wilson

Great Post! But, I would like to share my views about learning various languages, I feel ever since I got associated with language school Canada, I don’t have to put much effort while conversing any foreign language.

Leslie Wilson United States

6/25/2010 12:38:33 AM #

Leslie Wilson

Great Post! But, I would like to share my views about learning various languages, I feel ever since I got associated with language school Canada, I don't have to put much effort while conversing any foreign language.

Leslie Wilson United States

6/25/2010 12:54:20 AM #

coach handbags

Ive been meaning to read this and just never got a chance. Its an issue that Im very interested in, I just started reading and Im glad I did. Youre a great blogger, one of the best that Ive seen. This blog definitely has some information on topic that I just wasnt aware of. Thanks for bringing this stuff to light.

coach handbags United States

6/25/2010 5:35:32 AM #

fender custom shop stratocaster

I saw this discussion on a similar forum and really appreciate your take on it. You gave me a lot to think about

fender custom shop stratocaster United States

6/25/2010 8:21:55 AM #

online pharmacy online

Thanks for clearing that up for me, I think I kept putting it in the wrong row.

online pharmacy online United States

6/25/2010 8:23:59 AM #

patient assistance program

That may have been the same thing I was doing. It is pretty tricky if you are not paying close attention.

patient assistance program United States

6/25/2010 8:24:32 AM #

prescription

Very true.

prescription United States

6/26/2010 5:18:12 AM #

Black jack Tipps&Tricks

I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful and beneficial to your readers Nice article.

Black jack Tipps&Tricks India

7/3/2010 5:40:29 AM #

BMW X1

much as possible and mastering a select set of core skills - whatever they may be. These technologies are my suggestion for moving in that direction this year

BMW X1 United States

7/3/2010 7:26:52 AM #

Cordless Drills - Makita Drill

This blog is written so well that is very easy to read. The information is concise and you really make your point nicely. I was glad to come across this blog today as I will be winding up my search with all the information that I found here. Thanks for the share – Cheers - Becky

Cordless Drills - Makita Drill United States

7/5/2010 2:34:36 AM #

dental implant dentist

truly a gold mine. I have been wallowing on this for quite sometime and here I am reading about it! I will actually try these tips and let you know how they work out! Thanks again mate.

dental implant dentist United States

7/5/2010 11:45:55 PM #

tile roof repair

It’s really great post, nice blog..I would like to appreciate your work and would like to tell to my friends.

tile roof repair United States

7/6/2010 1:09:28 AM #

balance bikes

A good tips. I enjoyed reading it. I need to read more on this topic...I admiring time and effort you put in your blog, because it is obviously one great place where I can find lot of useful info..

balance bikes United States

7/7/2010 3:18:28 AM #

Astrology Capricorn

I don't usually reply on articles I read but I have to say this was just great. Keep up the good work.

Astrology Capricorn United States

7/7/2010 5:40:40 AM #

Used Auto Parts

I have the luxury of time to consider using the benefits these site can offer.....

Used Auto Parts United States

7/9/2010 5:10:02 AM #

Skin MD

Thanks for this awareness-raising post.I am very new on web development and so will certainly bookmark for my archive. Have a great day.

Skin MD United States

7/10/2010 2:02:20 AM #

anti wrinkle creams

A lot of answers that I found revolved around adding a event handler for mouse events in the template for a given DataGridColumn. That meant that I will have to attach these event handlers to all the columns.

anti wrinkle creams United States

7/10/2010 4:41:11 AM #

houston web design

It is a good blog , and its really informative.Comments are good in sites because this is one of the proof that your site is helpful to readers and many readers patronize your post.

houston web design United States

7/12/2010 3:16:39 AM #

carpet cleaning laguna beach

I was expecting some kind of direct method or property on some event that I could access to answer the question. It turned out that half of this question could be answered directly by using GetIndex method on DataGridRow object.

carpet cleaning laguna beach United States

7/13/2010 9:10:37 PM #

healthcare informatics

You gave nice ideas here. I done a research on the issue and learnt most peoples will agree with your blog. Certainly, these practices are unfair; but they say that most of their rules are only to apply to people who overdraw.

healthcare informatics United States

7/15/2010 2:10:57 AM #

BMW

Thanks for sharing these useful information! Hope that you will continue doing nice article like this. I will be one of your loyal reader if you maintain this kind of post!

BMW United States

7/15/2010 4:45:08 AM #

ROME APARTMENTS

I was very pleased to write the comment about it and also very excited.I wanted to thank you for this excellent read.. I hope we will see more from author in the future.

ROME APARTMENTS United States

7/15/2010 5:23:02 PM #

drug prices

Thanks for the tip, I had no idea how to determine that.

drug prices United States

7/15/2010 5:24:04 PM #

foreign pharmacy

That is very true, sometimes it can be really complicated.

foreign pharmacy United States

7/15/2010 5:24:32 PM #

prescriptions

Yea, I agree.

prescriptions United States

7/15/2010 10:56:35 PM #

audi a4

You gave nice ideas here. I done a research on the issue and learnt most peoples will agree with your blog. Certainly, these practices are unfair; but they say that most of their rules are only to apply to people who overdraw.

audi a4 United States

7/16/2010 4:56:39 AM #

Buy Cataclysm

wish I had found this blog before today. The advices in this posts are very helpful and I surely will read the other posts of this series too.Thank you for posting this. Your Blog is Bookmarked

Buy Cataclysm United States

7/17/2010 9:13:24 PM #

Search Engine Optimisation UK

a event handler for mouse events in the template for a given DataGridColumn. That meant that I will have to attach these event handlers to all the columns.

Search Engine Optimisation UK United States

7/18/2010 11:06:52 PM #

Link Building

The content connected with your site is precisely splendid, and your blog design is Simple generous. It seems like never dazzled. So great.

Link Building United States

7/19/2010 12:20:37 AM #

Vaginal Odor

Good detections shared. Me and my friend were arguing about an issue similar to this! Now I know that I was right. lol! Thanks for the information you post.

Vaginal Odor United States

7/21/2010 1:18:13 AM #

carpet cleaning harrisburg pa

It is a good blog , and its really informative.Comments are good in sites because this is one of the proof that your site is helpful to readers and many readers patronize your post.

carpet cleaning harrisburg pa United States

7/22/2010 3:59:23 AM #

dehydration

Well, the info your share here is great and informative to me as I am very new to the subject. But I love reading and getting some more knowledge on it. Thanks
reading

dehydration United States

7/22/2010 4:38:29 AM #

Source Naturals

Its amazing, looking at the time and effort you put into your blog and detailed information you provide. I'll bookmark your blog and visit it weekly for your new posts

Source Naturals United States

7/22/2010 8:15:20 PM #

used stationary bikes

I found this is an informative and interesting post so i think so it is very useful and knowledgeable. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. In fact your creative writing ability has inspired me. Really the article is reading its wings rapidly...

used stationary bikes United States

7/24/2010 1:07:05 AM #

Car Leasing

this blog before today. The advices in this posts are very helpful and I surely will read the other posts of this series too.Thank you for posting this. Your Blog is Bookmarked

Car Leasing United States

7/24/2010 5:36:58 AM #

Discount vitamin supplements

I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts.Any way Ill be subscribing to your feed and I hope you post again soon

Discount vitamin supplements United States

7/24/2010 11:29:09 AM #

Medical Tourism

post has been updated to work with the RTW version of the Silverlight 2 DataGrid

Medical Tourism United States

7/24/2010 9:36:19 PM #

Indian Lawyers

a wood fire worthily only when he warms his thoughts by it as well as his hands and feet. ~Odell Shepherd

Indian Lawyers United States

7/25/2010 3:04:46 AM #

Freelance SEO India

a wood fire worthily only when he warms his thoughts by it as well as his hands and feet. ~Odell Shepherd

Freelance SEO India United States

7/25/2010 7:55:55 AM #

cheap hosting

a wood fire worthily only when he warms his thoughts by it as well as his hands and feet. ~Odell Shepherd

cheap hosting United States

7/25/2010 7:18:53 PM #

personal loans

The post is written in very a good manner and it contains many useful information for me.

personal loans United States

7/25/2010 7:42:37 PM #

yeast infection treatment

post has been updated to work with the RTW version of the Silverlight 2 DataGrid

yeast infection treatment United States

7/26/2010 10:31:18 PM #

sagittarius taps

Its amazing, looking at the time and effort you put into your blog and detailed information you provide. I'll bookmark your blog and visit it weekly for your new posts

sagittarius taps United States

7/28/2010 9:11:56 AM #

Best SEO

I done a research on the issue and learnt most peoples will agree with your blog. Certainly, these practices are unfair; but they say that most of their rules are only to apply to people who overdraw.

Best SEO United States

Add Comment


(Will show your Gravatar icon)

  Country flag


  • Comment
  • Live Preview
Loading