如何将Datagridview的行值复制到同一Datagridview中的新行 [英] How to copy Row values of Datagridview into new row in the same Datagridview

查看:362
本文介绍了如何将Datagridview的行值复制到同一Datagridview中的新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




Hello,

Hello,


我有一个带有按钮的DataGridView(DataGridViewButtonColumn)。我希望每次单击按钮时,DataGridView中的选定行都会复制其值并直接插入同一行。我怎么能实现这个

I have a DataGridView with a Column that is filled with buttons (DataGridViewButtonColumn). I want that with every click on the button the selected row in the DataGridView ist copied with it´s values and inserted directly behind the same row. How can i realize this?


非常感谢提前!

Many thanks in advance!





推荐答案

你好,

到"复制"使用DataGridViewButtonColumn选择的行必须克隆当前行,然后使用Rows.Insert复制当前行下的行。下面的代码适用于没有数据源的DataGridView。

To "Copy" the selected row with a DataGridViewButtonColumn you must clone the current row then use Rows.Insert to copy the row under the current row. The code below works with a DataGridView w/o a DataSource.

using System;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    /// <summary>
    /// First column is a DataGridViewButton
    /// There are two DataGridViewTextBoColumn directly after the
    /// DatGridViewButton
    /// </summary>
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            Shown += Form1_Shown;
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            dataGridView1.Rows.Add(null, "Karen", "Payne");
            dataGridView1.Rows.Add(null, "Jim", "Gallagher");
            dataGridView1.Rows.Add(null, "Mary", "Adams");
            dataGridView1.Rows.Add(null, "Frank", "Jones");

            dataGridView1.CellContentClick += DataGridView1_CellContentClick;
        }

        private void DataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var senderGrid = (DataGridView)sender;

            if (senderGrid.CurrentRow != null && senderGrid.CurrentRow.IsNewRow)
            {
                return;
            }

            if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0)
            {
                senderGrid.Rows.Insert(senderGrid.CurrentRow.Index + 1, CloneWithValues(senderGrid.CurrentRow));

            }
        }
        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;
        }
    }
}


这篇关于如何将Datagridview的行值复制到同一Datagridview中的新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆