Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datagridview.SelectedCells order

I'm working on a C# application that contains a lot of DataGridViews which are empty. The user has to fill them with copy/pasted data from excel. What I do is the following:

int i = 0;
string s = Clipboard.GetText();

// Separate lines
string[] lines = Regex.Split(s, "\r\n");
foreach (string line in lines)
{
    // Separate each cell
    string[] cells = line.Split('\t');
    foreach (string cell in cells)
    {
        // If we selected as many cells as copied
        if (dataGridView.SelectedCells.Count == (lines.Length-1)*(cells.Length))
        {
            dataGridView.SelectedCells[i].Value = cell;
            i++;
        }
    }
}

The problem is that if I copy something like this (on excel):

1   2   3
4   5   6

My datagridview will look like:

6   4   2
5   3   1

I don't really know what to do to fix this... Thanks in advance

like image 583
Blowi Avatar asked Apr 11 '12 09:04

Blowi


People also ask

How to get row selected in DataGridView c#?

To get the selected rows in a DataGridView controlUse the SelectedRows property. To enable users to select rows, you must set the SelectionMode property to FullRowSelect or RowHeaderSelect.

What is DataGridView in C#?

The DataGridView control provides a customizable table for displaying data. The DataGridView class allows customization of cells, rows, columns, and borders through the use of properties such as DefaultCellStyle, ColumnHeadersDefaultCellStyle, CellBorderStyle, and GridColor.


2 Answers

  1. Convert your clipboard data to a 2-dimensional array. Remember length of each dimension.
  2. Iterate through the selected cells and find the top-left and bottom-right cells. From that you can determine it is of the right size.
  3. Using a double loop, map your clipboard data from array position directly to cell coordinate (not using selected cells) using the topleft cell coordinate as an offset.

Alternatively, rather than a 2 dimensional array, you could create a List of a small class/struct containing the properties Row, Col and Value. Then just iterate through that rather than the double loop.

like image 125
Lee Avatar answered Oct 01 '22 01:10

Lee


Replace

dataGridView.SelectedCells[i].Value = cell;

with

dataGridView.SelectedCells[(dataGridView.SelectedCells.Count-1) - i].Value = cell;

like image 25
Joshua Drake Avatar answered Oct 01 '22 01:10

Joshua Drake