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, "rn");
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


Replace

dataGridView.SelectedCells[i].Value = cell;

with

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


  • Convert your clipboard data to a 2-dimensional array. Remember length of each dimension.
  • 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.
  • 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.

    链接地址: http://www.djcxy.com/p/10674.html

    上一篇: Nuget:指定不添加引用的依赖关系

    下一篇: Datagridview.SelectedCells命令