2010-01-18 182 views

Respuesta

2

La clase DataGridViewRow tiene un método .Clone que clonará la fila actual que contiene.

Tener una mirada here para obtener más información

+0

Lo revisé. Pero después de copiar datos cuando los pego en una nueva fila de una vista de cuadrícula. No pega los datos de la fila anterior mientras que cuando pego en un solo cuadro de texto ... ocurre. Copio la función pegar código msdn después de la función de DataGridView. – Programmer

7

he encontrado un post que contiene código para pegar los valores de portapapeles en DataGridView.

yo estaba buscando en Google cómo pegar a DataGridView en C# desde el portapapeles, una información , copiado de Excel, y no encontrar respuesta completa. Recogidos un par de hilos de los foros y se le ocurrió esta respuesta, espero que hará más fácil vida. Usted no tiene que entender el código sólo debes copiar y pegar

A continuación se muestra una versión modificada de bits. Más allá de una pequeña refactorización, prohíbo pegar en las celdas de ReadOnly. ejemplo

Uso:

private void dataGridView1_KeyUp(object sender, KeyEventArgs e) 
{ 
    ClipboardUtils.OnDataGridViewPaste(sender, e); 
} 

Código:

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Windows.Forms; 

namespace Commons 
{ 
    public class ClipboardUtils 
    { 
     public static void OnDataGridViewPaste(object grid, KeyEventArgs e) 
     { 
      if ((e.Shift && e.KeyCode == Keys.Insert) || (e.Control && e.KeyCode == Keys.V)) 
      { 
       PasteTSV((DataGridView)grid); 
      } 
     } 

     public static void PasteTSV(DataGridView grid) 
     { 
      char[] rowSplitter = { '\r', '\n' }; 
      char[] columnSplitter = { '\t' }; 

      // Get the text from clipboard 
      IDataObject dataInClipboard = Clipboard.GetDataObject(); 
      string stringInClipboard = (string)dataInClipboard.GetData(DataFormats.Text); 

      // Split it into lines 
      string[] rowsInClipboard = stringInClipboard.Split(rowSplitter, StringSplitOptions.RemoveEmptyEntries); 

      // Get the row and column of selected cell in grid 
      int r = grid.SelectedCells[0].RowIndex; 
      int c = grid.SelectedCells[0].ColumnIndex; 

      // Add rows into grid to fit clipboard lines 
      if (grid.Rows.Count < (r + rowsInClipboard.Length)) 
      { 
       grid.Rows.Add(r + rowsInClipboard.Length - grid.Rows.Count); 
      } 

      // Loop through the lines, split them into cells and place the values in the corresponding cell. 
      for (int iRow = 0; iRow < rowsInClipboard.Length; iRow++) 
      { 
       // Split row into cell values 
       string[] valuesInRow = rowsInClipboard[iRow].Split(columnSplitter); 

       // Cycle through cell values 
       for (int iCol = 0; iCol < valuesInRow.Length; iCol++) 
       { 

        // Assign cell value, only if it within columns of the grid 
        if (grid.ColumnCount - 1 >= c + iCol) 
        { 
         DataGridViewCell cell = grid.Rows[r + iRow].Cells[c + iCol]; 

         if (!cell.ReadOnly) 
         { 
          cell.Value = valuesInRow[iCol]; 
         } 
        } 
       } 
      } 
     } 
    } 
} 
+0

Buen código.No está listo para el horario estelar, pero la mayor parte del camino hasta allí. Lo usé en un proyecto personal y funciona siempre y cuando deje lentamente la 'v' en ctrl + v primero, y la cuadrícula debe estar en EditMode of EditOnKeystrokeOrF2 – Mario

0

Copiar una fila a otra? ¿Por qué simplemente no ir a por ello como esto

public DataGridViewRow CloneWithValues(DataGridViewRow row) 
{ 
    DataGridViewRow clonedRow = (DataGridViewRow)row.Clone(); 
    for (Int32 index = 0; index < row.Cells.Count; index++) 
    { 
     clonedRow.Cells[index].Value = row.Cells[index].Value; 
    } 
    return clonedRow; 
} 

También puede hacer referencia a: http://canlu.blogspot.com/2009/06/copying-datagridviewrow-to-another.html

Espero que esto ayude! :}

0

continuación es mi versión modificada de alex2k8 respuesta esto funcionará para DataGridView enlazado.

aquí es la versión sin modificar

' Add rows into grid to fit clipboard lines 
     if (grid.Rows.Count < (r + rowsInClipboard.Length)) 
     { 
      grid.Rows.Add(r + rowsInClipboard.Length - grid.Rows.Count); 
     } 

aquí está mi esperanza modificación suceda alguien se ayudó aquí dt es una tabla de datos

' Add rows into grid to fit clipboard lines 
    If grid.Rows.Count < (r + rowsInClipboard.Length) Then 
     Dim workRow As DataRow 
     Dim i As Integer 

     For i = 0 To (r + rowsInClipboard.Length - grid.Rows.Count) 
      workRow = dt.NewRow() 
      workRow(0) = "" 

      dt.Rows.Add(workRow) 
     Next 
    End If 

NOTA: el código está en vb.net http://converter.telerik.com/ utilizar para convertir de nuevo a C#

Cuestiones relacionadas