c# - 如何使用按钮复制 Datagridview 中的行
问题描述
我有一个带有按钮的列的 DataGridView。现在我希望每次单击按钮时,DataGridView 中的选定行都会被复制并直接插入到选定行的后面。但是:我只想复制 2 个特定列的值。在这两个特定列之间,每次单击复制按钮时,都应使用从 1 开始手动输入到 2、3、4 等等的数字进行计数。其他列应为空。我怎么能意识到这一点?
提前谢谢了
解决方案
我希望它能完成工作
// 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;
}
}
推荐阅读
- serial-port - 从 ELB-REV4 上的 UART2 读取的示例 UART 代码
- docker - docker-machine create - 创建机器时出错:运行配置时出错:ssh 命令错误
- php - “While Loop”中的 PHP 函数“...几天前”不起作用
- python - Networkx:具有许多节点的网络
- javascript - 如何使用nodejs中的变量读取json结果
- xamarin - 删除 Xamarin.Forms 中导航栏上方的蓝条
- javascript - 如何通过 onclick 获得两个不同的事件?
- android - Android 中的切换按钮
- json.net - 是否可以使用 Json.NET 反序列化内联数组?
- c - 如何将修改后的数组保存到文件中