我有一个DataGridView,其中有一个用按钮填充的列。现在,我希望每次单击按钮都将复制DataGridView中的所选行并将其直接插入到所选行的后面。但是:我只想复制2个特定列的值。在这两个特定的列之间,从重复输入按钮开始,手动开始键入1到2、3、4等等的数字应该被计算在内。其他列应为空。我该如何实现?
非常感谢
答案 0 :(得分:0)
我希望它能完成工作
// 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;
}
}