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
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.
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.
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.
Replace
dataGridView.SelectedCells[i].Value = cell;
with
dataGridView.SelectedCells[(dataGridView.SelectedCells.Count-1) - i].Value = cell;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With