在datagridview中添加button按钮
.Net的DataGridView控件中,提供了一种列的类型,叫 DataGridViewButtonColumn ,这种列类型是展示为一个 按钮,可以给button赋予相应的text,并且,此button可以用来做处理事件的判断依据。
DataGridViewButtonColumn,虽然在UI展现上,是一个BUTTON的样子,但是,它的实际形态,并不是传统意义的BUTTON,而是渲染出来的样式,完全是painting的效果而已。所以,对于传统意义的BUTTON的那一套在这里都失效啦
代码实现:
//在datagridview中添加button按钮 DataGridViewButtonColumn btn = new DataGridViewButtonColumn(); btn.Name = "btnModify"; btn.HeaderText = "修改"; btn.DefaultCellStyle.NullValue = "修改"; dataGridView1.Columns.Add(btn);
然后在DataGridView的CellContentClick事件中写类似如下代码:
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("更新失败!"); } } }
C#.net. WPF.core 技术交流群 群号205082182,欢迎加入,也可以直接点击左侧和下方的"加入QQ群",直接加入