如何动态添加按钮名称和文本到gridview按钮? [英] How to add button name and text dynamically to gridview button?
本文介绍了如何动态添加按钮名称和文本到gridview按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已通过编程方式将登录按钮添加到DataGridView。我想检查数据库中的字段登录时间,如果为null,则按钮名称应为 login
,否则名称应为 logout
。
I have added login button to DataGridView programmatically. I want to check field logintime from database and if it is null the button name should be login
else it's name should be logout
.
private void frmAttendance_Load(object sender, EventArgs e)
{
GetData();//Fetch data from database
DataGridViewButtonColumn buttonLogin = new DataGridViewButtonColumn();
buttonLogin.Name = "Login";
buttonLogin.Text = "Login";
buttonLogin.UseColumnTextForButtonValue = true;
dataGridView1.Columns.Add(buttonLogin);
// Add a CellClick handler to handle clicks in the button column.
dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);
}
推荐答案
要添加按钮列,您可以:
var button=new DataGridViewButtonColumn();
button.Name="LoginButton";
button.HeaderText="Login";
button.Text = "Login";
button.UseColumnTextForButtonValue = true;
this.dataGridView1.Columns.Add(button);
动态设置按钮列的文本
要在每个按钮上显示登录文本,其足以设置:
To show "Login" text on each button, its enough to set:
button.Text = "Login";
button.UseColumnTextForButtonValue = true;
此外,如果您需要为按钮设置不同的文本,则可以使用 CellFormatting
DataGridView 事件并设置这些单元格的值:
Also if you need to set different text for buttons, you can use CellFormatting
event of DataGridView
and Set the value of those cells:
private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
//If this is header row or new row, do nothing
if (e.RowIndex < 0 || e.RowIndex == this.dataGridView1.NewRowIndex)
return;
//If formatting your desired column, set the value
if (e.ColumnIndex=this.dataGridView1.Columns["LoginButton"].Index)
{
//You can put your dynamic logic here
//and use different values based on other cell values, for example cell 2
//this.dataGridView1.Rows[e.RowIndex].Cells[2].Value
e.Value = "Login";
}
}
您应将此处理程序分配给 CellFormating
事件:
You should assign this handler to CellFormating
event:
this.dataGridView1.CellFormatting += dataGridView1_CellFormatting;
这篇关于如何动态添加按钮名称和文本到gridview按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文