- Declare Data table in global;
- Datatable hold temporary data;
DataTable dt = new DataTable();
- create column to datatable “dt”.
dt.Columns.Add("id");
dt.Columns.Add("name");
- Create temporary data and stored to datatable “dt”;
for (int i = 1; i < 21; i++)
{
dt.Rows.Add(DateTime.Now.ToString("hhmmssffffff")+"-"+i,
"Juan"+i+" Tamad"+i);
}
- Create button in datagridview.
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
dataGridView1.Columns.Add(btn);
btn.HeaderText = "Button";
btn.Text = "Button";
btn.Name = "btnClick";
btn.UseColumnTextForButtonValue = true;
btn.DisplayIndex = 0;
- Display date with button in datagridview;
dataGridView1.DataSource = dt;
- Hide button in datagridview or hide column in “Button”
dataGridView1.Columns[0].Visible = false;
- Show button in datagridview or hide column in “Button”
dataGridView1.Columns[0].Visible = true;
- All Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AddButtonInDataGridView
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
DataTable dt = new DataTable();
private void Form1_Load(object sender, EventArgs e)
{
dt.Columns.Add("id");
dt.Columns.Add("name");
for (int i = 1; i < 21; i++)
{
dt.Rows.Add(DateTime.Now.ToString("hhmmssffffff")+"-"+i,
"Juan"+i+" Tamad"+i);
}
DataGridViewButtonColumn btn = new DataGridViewButtonColumn();
dataGridView1.Columns.Add(btn); // .Columns.Add(btn);
btn.HeaderText = "Button";
btn.Text = "Button";
btn.Name = "btnClick";
btn.UseColumnTextForButtonValue = true;
btn.DisplayIndex = 0;
dataGridView1.DataSource = dt;
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Columns[0].Visible = true;
}
private void button2_Click(object sender, EventArgs e)
{
dataGridView1.Columns[0].Visible = false;
}
}
}
Related Topics
How to compose email and save email draft in outlook using C#
How to compose email and save email draft in outlook using C# […]
How to convert base64 string format of excel file into DataTable form of data type using C#
In this article, We learn how to convert base64 string format of excel file into Data Table form of data type using C#. I will […]
How to convert data from Aspose.Cells.Worksheet to DataTable using C#
How to conversion of data from Aspose.Cells.Worksheet to DataTable using C# […]