首页 > 解决方案 > 如何使用按钮复制 Datagridview 中的行

问题描述

在此处输入图像描述

我有一个带有按钮的列的 DataGridView。现在我希望每次单击按钮时,DataGridView 中的选定行都会被复制并直接插入到选定行的后面。但是:我只想复制 2 个特定列的值。在这两个特定列之间,每次单击复制按钮时,都应使用从 1 开始手动输入到 2、3、4 等等的数字进行计数。其他列应为空。我怎么能意识到这一点?

提前谢谢了

标签: c#winformsdatagridview

解决方案


我希望它能完成工作

// Enable AllowUserToAddRows
dgv.AllowUserToAddRows = true;

    private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
    {
        DataGridView dgv = sender as DataGridView;

        // If button clicked
        if (e.ColumnIndex == 0)
        {
            // Get values what you want to use, the Cell 2 is already increased
            var value1 = dgv.Rows[e.RowIndex].Cells[1].Value;
            var value2 = dgv.Rows[e.RowIndex].Cells[2].Value;

            // Define the maximum id and the row index of it
            int maxId = Convert.ToInt32(value2);
            int latestRowIndex = e.RowIndex;

            for (int i = 0; i < dgv.Rows.Count; i++)
            {
                // Select the highest id of selected item and get its row index
                if (dgv.Rows[i].Cells[1].Value == value1)
                {
                    maxId = Convert.ToInt32(dgv.Rows[i].Cells[2].Value);
                    latestRowIndex = i;
                }
            }

            // Insert a new row behind max id one
            dgv.Rows.Insert(latestRowIndex + 1);

            // Set the previously stored values and increase the stored Cell 2 value
            dgv.Rows[latestRowIndex + 1].Cells[1].Value = value1;
            dgv.Rows[latestRowIndex + 1].Cells[2].Value = maxId + 1;
        }
    }

推荐阅读