我已经以编程方式向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);
}
答案 0 :(得分:3)
要添加按钮列,您可以:
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;
此外,如果您需要为按钮设置不同的文字,则可以使用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;
答案 1 :(得分:1)
您可以循环播放DataGridView
:
foreach(DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCell cell = row.Cells[0] //Button column index.
//Put your data logic here.
cell.Value = "Login";
}
但在这种情况下,您必须知道DataGridViewButtonColumn