Foreword:
.Net's DataGridView control provides a column type called DataGridViewButtonColumn. This column type is displayed as a button, which can be assigned corresponding text, and this button can be used as a judgment basis for handling events.
Although the DataGridViewButtonColumn looks like a BUTTON in UI display, its actual form is not a BUTTON in the traditional sense, but a rendered style, which is completely the effect of painting. Therefore, the set of BUTTON in the traditional sense is invalid here.
Code:
//在datagridview中添加button按钮
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
btn.Name = "btnModify";
btn.HeaderText = "修改";
btn.DefaultCellStyle.NullValue = "修改";
dataGridView1.Columns.Add(btn);
Then write code similar to the following in the CellContentClick event of the DataGridView:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
//点击button按钮事件
if (dataGridView1.Columns[e.ColumnIndex].Name == "btnModify" && e.RowIndex >= 0)
{
//说明点击的列是DataGridViewButtonColumn列
DataGridViewColumn column = dataGridView1.Columns[e.ColumnIndex];
IPEntity ipentity = new IPEntity();
ipentity.ipName = Convert.ToString(dataGridView1.CurrentRow.Cells[0].Value);
ipentity.ipPart = Convert.ToString(dataGridView1.CurrentRow.Cells[1].Value);
ipentity.ipStart = Convert.ToString(dataGridView1.CurrentRow.Cells[2].Value);
ipentity.ipEnd = Convert.ToString(dataGridView1.CurrentRow.Cells[3].Value);
bool flag = selectIp.UpdateIP(ipentity);
if (flag)
{
MessageBox.Show("更新成功!");
}
else
{
MessageBox.Show("更新失败!");
}
}
}