C# DataGridViewButtonColumn 改变按钮的文本

本文介绍如何在DataGridView控件中使用DataGridViewButtonColumn,并通过编程方式动态更改按钮的显示文本。具体步骤包括设置ButtonColumn的基本属性、监听CellContentClick事件来实现文本更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

—————————————————————————————————

—————————————————————————————————

转载自:http://yueqing.blog.163.com/blog/static/3208259201191811715458/

        DataGridViewButtonColumn,虽然在UI展现上,是一个BUTTON的样子,但是,它的实际形态,并不是传统意义的BUTTON,而是渲染出来的样式,完全是painting的效果而已。所以,对于传统意义的BUTTON的那一套在这里都失效啦。

       1.设置DataGridViewButtonColumn的显示文本

填写该Column的Text,然后将UseColumnTextForButtonValue设为True,这样每个按钮都有自己的默认显示文本了。

       2.根据需要动态改变某个button显示的文本

实现的步骤:  

给DataGridView添加一列 DataGridViewButtonColumn,设置该列的属性如下:

DefaultCellStyle 的 NullValue 设置为 “启用”

UseColumnTextForButtonValue = False

其他属性自己根据需要设置

在DataGridView的CellContentClick事件中,写入如下的类似代码:

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
	//注释:
	//dataGridView1.Columns[e.ColumnIndex] is DataGridViewButtonColumn 说明点击的列是DataGridViewButtonColumn列
	//当然你也根据e.ColumnIndex == 你的按钮列的索引来做// e.RowIndex > -1 ,说明点击的不是列头
	if (dataGridView1.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex > -1)
	{
	    //获取当前被点击的单元格
	    DataGridViewButtonCell vCell = (DataGridViewButtonCell)dataGridView1.CurrentCell;
	    if (vCell.Tag == null) { vCell.Value = "停用"; vCell.Tag = true; }
	    //或者如下,两种实现效果一样,只是原理稍微有点区别
	    if (this.dgv_Meters.CurrentCell.Value.ToString() == "开始")
	    {
		this.dgv_Meters.CurrentCell.Value = "停止";
	    }
	    else
	    {
		this.dgv_Meters.CurrentCell.Value = "开始"; 
	    }
	}
}

以上转自:http://hi.baidu.com/322yali/blog/item/65e8bc1fc474bc13304e15f1.html




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值