gpt4 book ai didi

c# - 如何将按钮名称和文本动态添加到 gridview 按钮?

转载 作者:行者123 更新时间:2023-11-30 20:40:38 24 4
gpt4 key购买 nike

我已通过编程方式将登录按钮添加到 DataGridView。我想检查数据库中的登录时间字段,如果它为空,则按钮名称应为 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);

动态设置按钮栏文字

要在每个按钮上显示“登录”文本,设置就足够了:

button.Text = "Login";
button.UseColumnTextForButtonValue = true;

此外,如果您需要为按钮设置不同的文本,您可以使用 DataGridViewCellFormatting 事件并设置这些单元格的值:

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;

关于c# - 如何将按钮名称和文本动态添加到 gridview 按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33166226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com