DataGridview中的行复制/粘贴功能(Windows应用程序)

Pro*_*er 9 datagridview

我正在开发一个C#windows应用程序,并希望在DataGridView中复制一行并将其粘贴到一个新行中.我怎么能做到这一点?我正在使用.net framework 3.5.

能否请您提供一些想法或一些代码,以表明我如何实现这一目标?

ale*_*2k8 7

我找到了一个帖子,其中包含将值从剪贴板粘贴到DataGridView中的代码.

我正在谷歌搜索如何从剪贴板粘贴到C#中的DataGridView,一个信息,从Excel复制,并没有找到完整的答案.收集了来自论坛的几个主题并提出了这个答案,希望它能让人们的生活更轻松.你不必理解代码只需复制和粘贴

下面是一个有点修改的版本.除了小的重构,我禁止粘贴到ReadOnly单元格中.

用法示例:

private void dataGridView1_KeyUp(object sender, KeyEventArgs e)
{
    ClipboardUtils.OnDataGridViewPaste(sender, e);
}
Run Code Online (Sandbox Code Playgroud)

码:

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];
                        }
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ton*_*ion 2

DataGridViewRow 类有一个 .Clone 方法,它将克隆它所保存的当前行。

看看这里了解更多信息