Try to Create On Click event on the button created with new record in datagridview

Trying to create on click Listener on the button created with each record in dataGridView

OleDbConnection connection = new OleDbConnection();


OleDbCommand command = new OleDbCommand();

command.Connection = connection;

command.CommandText = "SELECT * FROM vc";

OleDbDataAdapter da = new OleDbDataAdapter(command);

DataTable dt = new DataTable();


dataGridView1.DataSource = dt;

DataGridViewButtonColumn col = new DataGridViewButtonColumn();

col.UseColumnTextForButtonValue = true; 

col.Text = "Folder";

col.Name = "MyButton";


1 answer

  • answered 2018-01-13 17:21 Ehsan Ullah Nazir

    You need to look at DataGridView.CellClick Event

    1. Try following code to add button ,

      // Add a button column. 
      DataGridViewButtonColumn buttonColumn = 
          new DataGridViewButtonColumn();
      buttonColumn.HeaderText = "";
      buttonColumn.Name = "MyButton";
      buttonColumn.Text = "Folder"; 
      buttonColumn.UseColumnTextForButtonValue = true;
    2. CellClick handler

      // Add a CellClick handler to handle clicks in the button column.
      dataGridView1.CellClick +=
          new DataGridViewCellEventHandler(dataGridView1_CellClick);
    3. And yes dataGridView1_CellClick itself for you stuff to work against a buttion click.One thing need to look at is ,

    You must need to look for button cell clicked, else it will be fired for each cell content click.

        void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
            // Ignore clicks that are not on button cells. 
            if (e.RowIndex < 0 || e.ColumnIndex !=
                dataGridView1.Columns["myButton"].Index) return;
           you stuff....