Tikam Sangwani
Tikam Sangwani

Reputation: 325

Add button control in current cell of datagrid view control

I want to add a custom control(Button) in current cell of Datagridview control. i have created the custom control(Button). My requirement is when i clicking any cell of the Datagridview, this control should show on that cell. here is the screen shot of this.

enter image description here

Please help me to overcome this problem. Any help appreciated.

NOTE:- This button is not a drop down button. It is just a simple button with drop down image. By clicking on this button a popup window will be open.

Upvotes: 1

Views: 3942

Answers (1)

King King
King King

Reputation: 63317

You just need 1 button, set its Parent to your DataGridView and update its location according to the current cell bounds. This should be done in the CellPainting event handler, like this:

Button button = new Button(){Width = 20, Height = 20};
int maxHeight = 20;
button.Parent = dataGridView1;//place this in your form constructor
//CellPainting event handler for both your grids
private void dataGridViews_CellPainting(object sender,
                                        DataGridViewCellPaintingEventArgs e) {
  DataGridView grid = sender as DataGridView;
  if (grid.CurrentCell.RowIndex == e.RowIndex &&
      grid.CurrentCell.ColumnIndex == e.ColumnIndex) {
     button.Top = e.CellBounds.Top - 2;
     button.Left = e.CellBounds.Right - button.Width;
     button.Height = Math.Min(e.CellBounds.Height, maxHeight);
     button.Invalidate();
  }
}
//Enter event handler for both your grids
private void dataGridViews_Enter(object sender, EventArgs e){
  button.Parent = (sender as Control);
}

NOTE: the CellPainting event handler (used for both grids) above should do something with the button only, if you add some other code such as for painting, both the grids will be effected by that code.

Upvotes: 2

Related Questions