ehoho

EXCEL TO DATAGRIDVIEW copy-paste

Jun 17th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.59 KB | None | 0 0
  1. // Код для копипаста с экселя в грид
  2.  
  3.         void grid_KeyDown(object sender, KeyEventArgs e)
  4.         {
  5.             if (e.Control && e.KeyCode == Keys.C)
  6.             {
  7.                 DataObject d = dataGridView1.GetClipboardContent();
  8.                 Clipboard.SetDataObject(d);
  9.                 e.Handled = true;
  10.             }
  11.             else if (e.Control && e.KeyCode == Keys.V)
  12.             {
  13.                 string s = Clipboard.GetText();
  14.                 string[] lines = s.Split('\n');
  15.                 int row = dataGridView1.CurrentCell.RowIndex;
  16.                 int col = dataGridView1.CurrentCell.ColumnIndex;
  17.                 foreach (string line in lines)
  18.                 {
  19.                     if (row < dataGridView1.RowCount && line.Length > 0)
  20.                     {
  21.                         string[] cells = line.Split('\t');
  22.                         for (int i = 0; i < cells.GetLength(0); ++i)
  23.                         {
  24.                             if (col + i <  this.dataGridView1.ColumnCount)
  25.                             {
  26.                                 dataGridView1[col + i, row].Value = Convert.ChangeType(cells[i], dataGridView1[col + i, row].ValueType);
  27.                             }
  28.                             else
  29.                             {
  30.                                 break;
  31.                             }
  32.                         }
  33.                         row++;
  34.                     }
  35.                     else
  36.                     {
  37.                         break;
  38.                     }
  39.                 }
  40.             }
  41.         }
Advertisement
Add Comment
Please, Sign In to add comment