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);
}
To add a button column you can:
var button=new DataGridViewButtonColumn();
button.Name="LoginButton";
button.HeaderText="Login";
button.Text = "Login";
button.UseColumnTextForButtonValue = true;
this.dataGridView1.Columns.Add(button);
To set text of button column dynamically
To show "Login" text on each button, its enough to set:
button.Text = "Login";
button.UseColumnTextForButtonValue = true;
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";
}
}
You should assign this handler to CellFormating
event:
this.dataGridView1.CellFormatting += dataGridView1_CellFormatting;
You can go hrough the DataGridView
in a loop:
foreach(DataGridViewRow row in dataGridView1.Rows)
{
DataGridViewCell cell = row.Cells[0] //Button column index.
//Put your data logic here.
cell.Value = "Login";
}
But in this case, you have to know the column index of your DataGridViewButtonColumn
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.