how to get Datagridview selected cells in ordered by their column
<p>I have a table with columns c1 .. c4 and with a row containing data such as</p>

<p>c1 c2 c3 c4</p>

<p>[CAN][YOU][HELP][ME]</p>

<p>Multiselect is on. When I get datagridview.SelectedCells then they will be in the list in order of when they were selected. E.g. I select HELP and then YOU the list will be HELP followed by YOU. However I need a list to show YOU,HELP because YOU is from a column before HELP. If I would select YOU,HELP,CAN in that order then the list should be CAN,YOU,HELP because CAN is in c1, YOU in c2 and HELP in c3.</p>

<p>How can I do this? Thank you for your help.</p>

<p>Chris</p>

<p>Hi here is the code. The order of the selected cell list depends on how you select them - e.g. start left to right or vice versa. As you can see from the code, I have found a workaround. The OrderBy idea is much more elegant but I believe it only works for Rows and not for cells.  </p>

<p>private void attribute_treeview_DragDrop(object sender, DragEventArgs e)
        {
            // dropped item from either datagridview into treeview</p>

<pre><code>        if (e.Data.GetDataPresent(typeof(List&lt;string&gt;)))
        {
            // Determine which category the item was draged to
            Point p = attribute_treeview.PointToClient(new Point(e.X, e.Y));
            TreeNode destinationNode = attribute_treeview.GetNodeAt(p);

            // sort selected cells based on position in productname
            var selected_cells = e.Data.GetData(typeof(List&lt;string&gt;)) as List&lt;string&gt;;
            SortedDictionary&lt;int, string&gt; orderedcellcontents = new SortedDictionary&lt;int, string&gt;();

            ProductItem pitem = new ProductItem((BsonDocument)productlist.SelectedItems[0].Tag);

            foreach (var element in selected_cells)
            {
                int pos = Array.IndexOf(pitem.tokens, element);
                if (!orderedcellcontents.ContainsKey(pos))
                    orderedcellcontents.Add(pos, element);
            }

            if (PopulateTreeview(destinationNode, orderedcellcontents.Values.ToList&lt;string&gt;())) 
            {
                dictionary_haschanged = true;
                destinationNode.Expand();
            }

        }
</code></pre>