DataGridView中实现复制、剪切、粘贴功能

时间:2022-03-20 08:22:58

  用户在使用WinForms应用程序时,为了快速的输入数据,通常会在DataGridView与Excle之间进行复制、剪切、粘贴操作。将Excel中的数据复制到DataGridView时,直接使用Excel中的复制、剪切功能,需要在DataGridView中实现粘贴功能;将DataGridView中数据复制到DataGridView或Excel中时,需要在DataGridView中实现复制、剪切、粘贴功能。

   DataGridView.ClipboardCopyMode 属性被设定为 DataGridViewClipboardCopyMode.Disable 以外的情况时,「Ctrl + C」 按下的时候,被选择的单元格的内容会拷贝到系统剪切板内(DataGridView已提供了复制方法),可以直接粘贴到Excel 中,但在DataGridView中没有提供粘贴方法,需要自己定义。

  以下分别演示在DataGridView中实现复制、剪切、粘贴功能:

        /// <summary>
        /// 实现复制功能,将DataGridView中选定单元格的值复制到剪贴板中
        /// </summary>
        /// <param name="dgv_Test"></param>
        private void CopyData(DataGridView dgv_Test)
        {
            Clipboard.SetDataObject(dgv_Test.GetClipboardContent());
        }

        /// <summary>
        /// 实现剪切功能,将DataGridView中选定单元格的值复制到剪贴板中,并将选中的单元格的值清空
        /// </summary>
        /// <param name="dgv_Test"></param>
        private void CutData(DataGridView dgv_Test)
        {
            //将选定单元格的值复制到剪贴板中
            Clipboard.SetDataObject(dgv_Test.GetClipboardContent());

            string clipboardText = Clipboard.GetText(); //获取剪贴板的内容
            if (string.IsNullOrEmpty(clipboardText))
            {
                return;
            }
            int colnum = 0;
            int rownum = 0;
            for (int i = 0; i < clipboardText.Length; i++)
            {
                if (clipboardText.Substring(i,1) == "\t")
                {
                    colnum++;
                }
                if (clipboardText.Substring(i,1) == "\n")
                {
                    rownum++;
                }
            }
            //粘贴板上的数据来源于EXCEL时,每行末尾都有\n,来源于DataGridView是,最后一行末尾没有\n
            if (clipboardText.Substring(clipboardText.Length-1,1) == "\n")
            {
                rownum--;
            }
            colnum = colnum / (rownum + 1);
            //获取当前选中的最后一个单元格的列、行序号
            int colIndex = dgv_Test.SelectedCells[0].ColumnIndex;
            int rowIndex = dgv_Test.SelectedCells[0].RowIndex;
            for (int i = 0; i <= rownum; i++)
            {
                for (int j = 0; j <= colnum; j++)
                {
                    dgv_Test.Rows[rowIndex - i].Cells[colIndex - j].Value = "";
                }
            }
        }

        /// <summary>
        /// 实现粘贴功能,将剪贴板中的内容粘贴到DataGridView中
        /// </summary>
        /// <param name="dgv_Test"></param> 
        private void PasteData(DataGridView dgv_Test)
        {
            try
            {
                string clipboardText = Clipboard.GetText(); //获取剪贴板中的内容
                if (string.IsNullOrEmpty(clipboardText))
                {
                    return;
                }
                int colnum = 0;
                int rownum = 0;
                for (int i = 0; i < clipboardText.Length; i++)
                {
                    if (clipboardText.Substring(i,1) == "\t")
                    {
                        colnum++;
                    }
                    if (clipboardText.Substring(i,1) == "\n")
                    {
                        rownum++;
                    }
                }
                //粘贴板上的数据来源于EXCEL时,每行末尾都有\n,来源于DataGridView是,最后一行末尾没有\n
                if (clipboardText.Substring(clipboardText.Length-1,1) == "\n")
                {
                    rownum--;
                }
                colnum = colnum / (rownum + 1);
                object[,] data; //定义object类型的二维数组
                data = new object[rownum + 1, colnum + 1];  //根据剪贴板的行列数实例化数组
                string rowStr = "";
                //对数组各元素赋值
                for (int i = 0; i <= rownum; i++)
                {
                    for (int j = 0; j <= colnum; j++)
                    {                     
                        //一行中的其它列
                        if (j != colnum)
                        {
                            rowStr = clipboardText.Substring(0, clipboardText.IndexOf("\t"));
                            clipboardText = clipboardText.Substring(clipboardText.IndexOf("\t") + 1);
                        }
                        //一行中的最后一列
                        if (j == colnum && clipboardText.IndexOf("\r") != -1)
                        {
                            rowStr = clipboardText.Substring(0, clipboardText.IndexOf("\r"));
                        }
                        //最后一行的最后一列
                        if (j == colnum && clipboardText.IndexOf("\r") == -1)
                        {
                            rowStr = clipboardText.Substring(0);
                        }
                        data[i, j] = rowStr;
                    }
                    //截取下一行及以后的数据
                    clipboardText = clipboardText.Substring(clipboardText.IndexOf("\n") + 1);
                }
                //获取当前选中单元格的列序号
                int colIndex = dgv_Test.CurrentRow.Cells.IndexOf(dgv_Test.CurrentCell);
                //获取当前选中单元格的行序号
                int rowIndex = dgv_Test.CurrentRow.Index;
                for (int i = 0; i <=rownum; i++)
                {
                    for (int j = 0; j <= colnum; j++)
                    {
                        dgv_Test.Rows[i + rowIndex].Cells[j + colIndex].Value = data[i, j];
                    }
                }
            }
            catch
            {
                MessageBox.Show("粘贴区域大小不一致");
                return;
            }
        }

 

    //测试代码

        private void tsmi_Copy_Click(object sender, EventArgs e)
        {
            CopyData(dgv_PersonInfo);
        }

        private void tsmi_Cut_Click(object sender, EventArgs e)
        {
            CutData(dgv_PersonInfo);
        }

        private void tsmi_Paste_Click(object sender, EventArgs e)
        {
            PasteData(dgv_PersonInfo);
        }

一本深入了解CLR和.NET Framework的C#经典书籍,值得有一定基础的人员所拥有,在此推荐给大家。

http://s.click.taobao.com/t?e=zGU34CA7K%2BPkqB07S4%2FK0CFcRfH0GoT805sipKjy4P%2BQfuysWenw8LZY0QbMN7a1qMRwojQNUZuLcyGxfO4L4GExK79geXK7z3bd7n%2BCeOIMog%3D%3D