Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to handle Click Even in button on Dynamic DataGrid

Status
Not open for further replies.

kgreer

MIS
Jul 18, 2003
155
US
I have dynamically built a datagrid in a TabControl. I am now adding a button to allow the user to edit the information. The button shows up just fine, but when I click on the button the Click event is not being called. Below is my code for adding the button.

// The tabpage.
TabPage newPage = new TabPage(drCurrent[0].ToString());

newPage.Text = drCurrent[0].ToString();

DataGridView grid = new DataGridView();
grid.AllowUserToAddRows = false;
grid.AllowUserToDeleteRows = false;


DataGridViewButtonColumn bcol = new DataGridViewButtonColumn();
bcol.HeaderText = "Edit";
bcol.Text = "Edit";
bcol.Name = "btnClickMe";
bcol.Width = 50;
bcol.UseColumnTextForButtonValue = true;

grid.Columns.Add(bcol);


grid.Dock = DockStyle.Fill;

grid.DataSource = table;


newPage.Controls.Add(grid);

// Add to the tab control.
tabMain.TabPages.Add(newPage);


What do I need to do to get the click even working?
 
Where do you assign the click event to the button? If you are dynamically adding the button you will need to assign the click event to it the way the designer does it.

this.button1.Click += new System.EventHandler(this.button1_Click);

However since it is a datagrid field you would assign it to the cell content click event of the DGV.

grid.Columns.Add(bcol);

grid.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.grid_CellContentClick);

grid.Dock = DockStyle.Fill;

I did get some unexpected results when testing this though. It would occasionally fire the event when clicking on a random column in the grid. Did not troubleshoot further to figure out why but it did consistently fire the event when clicking the edit button.


 
bakershawm

Thanks for the reply.... I finally did exactly what you said by using the click event.
I am not getting any issues showing up, it is working just fine on my end.

dataGridView1.CellContentClick += new DataGridViewCellEventHandler(this.dataGridView1_CellClick);
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top