Datagridview.SelectedCells顺序

我正在处理一个C#应用程序,其中包含大量的空DataGridViews。 用户必须填写来自Excel的复制/粘贴数据。 我做的是以下几点:

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++; } } } 

问题是,如果我复制这样的东西(在Excel中):

 1 2 3 4 5 6 

我的datagridview将如下所示:

 6 4 2 5 3 1 

我真的不知道该怎么办才能解决这个问题…提前致谢

更换

dataGridView.SelectedCells[i].Value = cell;

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

  1. 将您的剪贴板数据转换为二维数组。 记住每个维度的长度。
  2. 遍历选定的单元格,并find左上angular和右下angular的单元格。 从中你可以确定它是正确的大小。
  3. 使用双循环,将剪贴板数据从数组位置直接映射到单元格坐标(不使用选定的单元格),使用单元格坐标作为偏移量。

或者,您可以创build一个包含Row,Col和Value属性的小类/结构的列表,而不是一个二维数组。 然后只是遍历,而不是双循环。