First you need to create New Project and give the Name of the project “DataGridViewAddButton”. Add the command button,dataGridView control on Form and change the command button name CmdAddbuttom and dataGridView name dataGrid then copy this code and paste. So please change the datasource name,database name and Table name.
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
usingSystem.Data.SqlClient;
namespaceDataGridViewAddButton
{
public partial class Form1 : Form
{
stringcon = “Data Source=ServerName;Initial Catalog=Northwind;Integrated Security=True”;
publicForm1()
{
InitializeComponent();
}
privatevoid CmdAddbuttom_Click(object sender, EventArgs e)
{
stringsql=“Select Employeeid,FirstName,LastName from Employees”;
SqlConnectioncnn = new SqlConnection(con);
SqlDataAdaptersd = new SqlDataAdapter(sql, cnn);
DataSetds = new DataSet();
cnn.Open();
sd.Fill(ds, “Employees”);
cnn.Close();
dataGrid.DataSource = ds;
dataGrid.DataMember = “Employees”;
DataGridViewButtonColumn cmdbtn = new DataGridViewButtonColumn();
dataGrid.Columns.Add(cmdbtn);
cmdbtn.HeaderText = “Click Data”;
cmdbtn.Text = “Click Here”;
cmdbtn.Name = “Button”;
cmdbtn.UseColumnTextForButtonValue = true;
}
privatevoid dataGrid_CellClick(object sender, DataGridViewCellEventArgse)
{
if(e.ColumnIndex ==3)
{
MessageBox.Show(dataGrid.Rows[e.RowIndex].Cells[“FirstName”].Value.ToString()
+ “ Button Clicked” );
}
}
}