以下是一个示例代码,展示如何在编辑单元格事件中编辑相邻单元格:
using System;
using System.Windows.Forms;
namespace DataGridViewExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
// 获取当前编辑的单元格的行和列索引
int rowIndex = e.RowIndex;
int columnIndex = e.ColumnIndex;
// 编辑相邻的右边单元格
if (columnIndex < dataGridView1.ColumnCount - 1)
{
DataGridViewCell adjacentCell = dataGridView1.Rows[rowIndex].Cells[columnIndex + 1];
adjacentCell.Value = "Edited";
}
// 编辑相邻的下方单元格
if (rowIndex < dataGridView1.RowCount - 1)
{
DataGridViewCell adjacentCell = dataGridView1.Rows[rowIndex + 1].Cells[columnIndex];
adjacentCell.Value = "Edited";
}
}
}
}
在这个示例中,我们使用dataGridView1_CellEndEdit
事件来处理当用户编辑完一个单元格时的逻辑。首先,我们获取当前编辑的单元格的行和列索引。然后,我们检查当前单元格是否有一个右边的相邻单元格,如果有,我们将其值设置为"Edited"。接下来,我们检查当前单元格是否有一个下方的相邻单元格,如果有,我们将其值设置为"Edited"。这样,用户在编辑一个单元格时,相邻的单元格也会被自动编辑。