如何动态添加按钮名称和文本到gridview按钮
本文关键字:按钮 文本 gridview 添加 何动态 动态 | 更新日期: 2023-09-27 18:17:55
我以编程方式添加了登录按钮到DataGridView。我想检查字段logintime从数据库,如果它是空的按钮名称应该是login
,否则它的名称应该是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);
动态设置按钮列文本
要在每个按钮上显示"Login"文本,只需设置:
button.Text = "Login";
button.UseColumnTextForButtonValue = true;
如果你需要为按钮设置不同的文本,你可以使用CellFormatting
事件的DataGridView
和设置这些单元格的值:
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
事件:
this.dataGridView1.CellFormatting += dataGridView1_CellFormatting;
您可以在循环中遍历DataGridView
:
foreach(DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCell cell = row.Cells[0] //Button column index.
//Put your data logic here.
cell.Value = "Login";
}
但是在这种情况下,你必须知道DataGridViewButtonColumn