winform中在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("更新失败!");
                }
            }           
        }

效果图如下:

 

  • 7
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Winform,可以通过以下步骤为DataGridView添加编辑和删除按钮: 1. 首先,确保已在窗体上添加DataGridView控件,并将其命名为dataGridView。 2. 添加编辑按钮: - 在窗体上添加Button控件,并设置其Text为“编辑”。 - 双击编辑按钮,进入按钮的点击事件处理方法。 - 在事件处理方法,使用以下代码实现当用户点击编辑按钮时,获取选行的数据,并进行编辑: ```csharp private void editButton_Click(object sender, EventArgs e) { if(dataGridView.SelectedRows.Count > 0) { DataGridViewRow selectedRow = dataGridView.SelectedRows[0]; // 获取选行的数据 string data = selectedRow.Cells["ColumnName"].Value.ToString(); // 进行编辑操作 // ... } } ``` 3. 添加删除按钮: - 在窗体上添加Button控件,并设置其Text为“删除”。 - 双击删除按钮,进入按钮的点击事件处理方法。 - 在事件处理方法,使用以下代码实现当用户点击删除按钮时,删除选行的数据: ```csharp private void deleteButton_Click(object sender, EventArgs e) { if(dataGridView.SelectedRows.Count > 0) { DataGridViewRow selectedRow = dataGridView.SelectedRows[0]; // 删除选行的数据 dataGridView.Rows.Remove(selectedRow); } } ``` 通过以上步骤,就可以为DataGridView添加编辑和删除按钮了。在实际操作,您可以根据具体需求对代码进行适当调整和完善。另外,还可以根据需要设置按钮的位置、样式等来符合设计要求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值