473,320 Members | 1,848 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,320 developers and data experts.

(C# WPF) DataGrid Invert Row Selection...

Aimee Bailey
197 Expert 100+
Ok today I came across one of the oddest problems so far in my programming life, I was building an application not to dissimilar to a file explorer, and I had the need to invert the row selection on the DataGrid control, something easy you say? well give it a go and you'll soon come across the same issue. The problem was that there is no specified way to do this, plus a search on Google showed that not many people have needed this yet, so I was stuck having to write a routine myself, this insight is the result of my efforts in hope that no one else has to go through hours trying to do the same thing.

First of all, we'll assume that the DataGrid we are using is bound to a list of classes called DummyDataItem as below:

Expand|Select|Wrap|Line Numbers
  1. class DummyDataItem
  2. {
  3.     public string Name { get; set; }
  4.  
  5.     public DummyDataItem(string name)
  6.     {
  7.         Name = name;
  8.     }
  9. }
  10.  

Ok so here is one of the first methods i tried...

Expand|Select|Wrap|Line Numbers
  1. public void InvertA()
  2. {
  3.     foreach (object o in dataGrid1.Items)
  4.     {
  5.         DataGridRow row = o as DataGridRow;
  6.         if (row.IsSelected == true)
  7.         {
  8.             row.IsSelected = false;
  9.         }
  10.         else
  11.         {
  12.             row.IsSelected = true;
  13.         }
  14.     }
  15. }
  16.  

At first glance this method may seem completely reasonable, we do a light cast so that we can check weather the row is selected or not, then invert it on an item by item basis. However give it a run, and you'll soon find that items in the DataGrid actually can't be cast to a DataGridRow! hmm, we'll have to try something else...

Expand|Select|Wrap|Line Numbers
  1. public void InvertB()
  2. {
  3.     var selected = dataGrid1.SelectedItems;
  4.     dataGrid1.SelectAll();
  5.  
  6.     for (int x = 0; x < selected.Count; x++)
  7.     {
  8.         dataGrid1.SelectedItems.Remove(selected[x]);
  9.     }
  10. }
  11.  

A shorter sub, looks neat and tidy, and this time we get no runtime errors :D but oops, now it's selecting a load of random ones... wonderful. Clearly something is going wrong, and the more experienced of you may notice that "var selected" actually only references the selected items. This means when we iterate over the selected items, the list has changed and keeps on changing during the loop, we can't use this.

Lastly the way that works, from my last example, you can see that we were half way there, however we need to work with a reference list that does not change as we are inverting. So if we cast each selected item to it's base class, and add one of the classes properties preferably a string as strings are read only to a list, we can keep track of which items to remove from the selection (after select all).

Expand|Select|Wrap|Line Numbers
  1. public void InvertC()
  2. {
  3.     List<string> names = new List<string>();
  4.     foreach (object o in dataGrid1.SelectedItems)
  5.     {
  6.         names.Add((o as DummyDataItem).Name);
  7.     }
  8.  
  9.     dataGrid1.SelectAll();
  10.  
  11.     foreach (object z in dataGrid1.Items)
  12.     {
  13.         if (names.Contains<string>((z as DummyDataItem).Name))
  14.         {
  15.             dataGrid1.SelectedItems.Remove(z);
  16.         }
  17.     }
  18. }
  19.  

In this example, we grab the name from each DummyDataItem that is currently selected, select all the items, then pick out based on a name comparison which items do not belong in the DataGrid's SelectedItems property.

For now this seems the most sensible way to accomplish this task, I hope someone finds this useful, and If anyone has any better solutions, please feel free to share them also.

Aimee Bailey.
Mar 4 '11 #1
1 7802
hello, try this >
Expand|Select|Wrap|Line Numbers
  1. for (int i = 0; i < dataGrid1.Items.Count; i++)
  2. {
  3.     DataGridRow row = (DataGridRow)dataGrid1.ItemContainerGenerator.ContainerFromIndex(i);
  4.  
  5.     if (row.IsSelected == true)
  6.     {
  7.         row.IsSelected = false;
  8.     }
  9.     else
  10.     {
  11.         row.IsSelected = true;
  12.     }
  13. }
Sep 30 '11 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Ahmet AKGUN | last post by:
Hi; How can we get multiple selections on a datagrid ? There is one property called CurrentRowIndex but it always retrieves last selection. On grid I have lots of selections, all selected using...
0
by: MrNobody | last post by:
You know how if you click the RowHeader of a DataGrid, it selects the entire row? How can I set my DataGrid to act like that whenever I click a column within the row? Also, how can I make it so...
2
by: ___Newbie___ | last post by:
Hello, I'm looking for a control that can display rows and columns similar to a table but highlight the entire row during selection? Listbox highlights the entire row but doesn't support...
1
by: Bidarkota | last post by:
can i select all the rows in a datagrid with a color when i check the checkbox in the datagrid header. can i do this at client side. i need to delete all the selected rows when i click on a delete...
0
by: Bidarkota | last post by:
Can i set the color of the entire DataGrid Column (for example to blue) when i click the header of the DataGrid Column. If it is possible please help with sample code. Thanks in Advance.
2
by: rodchar | last post by:
Hey all, I have a datagrid that has a select column. I've bound an untyped data table to the datagrid and was just wondering how I would get to all the values of a row when a user selects a row?...
5
by: Genojoe | last post by:
I am using code from Help with two exceptions. (1) I increased the number of sample rows from 3 to 20, and (2) I anchored the datagrid to bottom of form so that I can change the size of the grid by...
0
by: Jennifer | last post by:
I had this beautiful datagrid on an ASP page (VB.Net as the code behind). When I clicked on a Select Button, the row was selected and the background color changed the way it was supposed to. The...
2
by: Jorge | last post by:
Hi Does Datagrid support multiple selection? If not please suggest some that does like the old msflexgrid. Thanks. Kind Regards
0
by: slinky | last post by:
I'm using VS2003 VB.net/ASP.net and have a Datagrid on an .ASPX page that is successfully displaying the records I was expecting. The next step I want to do is to double-click a line (record) and...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.