Order Datagridview.SelectedCells

I am working on a C # application that contains many DataGridViews that are empty. The user must fill them with copied / pasted data from excel. I do 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 this:

 6 4 2 5 3 1 

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

+7
source share
2 answers

Replace

dataGridView.SelectedCells[i].Value = cell;

from

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

+1
source
  • Convert clipboard data to a two-dimensional array. Remember the length of each dimension.
  • Scroll through the selected cells and find the left and bottom right cells. From this you can determine that it is the right size.
  • Using a double loop, map the clipboard data from the array position directly to the cell coordinate (without using the selected cells), using the topleft cell coordinate as the offset.

Alternatively, instead of a 2-dimensional array, you can create a list of a small class / structure containing the Row, Col, and Value properties. Then just repeat this, not a double loop.

+2
source

All Articles