I have an event that triggers upon a treeview node click, this then creates a datagridview and adds it to a panel:
void tvd_NodeClickEvent(double animal, string experiment, string pluginIdentifier)
{
DataGridDisplay dgv = new DataGridDisplay(panel4);
dgv.addDatagrid(animal, experiment, pluginIdentifier);
}
I try to remove the old datagrid by doing the following:
panel4.Controls.Remove(datagrid);
panel4.Invalidate();
And then adding the new datagrid:
panel4.Controls.Add(datagrid);
The problem is, the datagrids are drawing themselves on top of eachother without removing the old one?开发者_如何学JAVA Any ideas?
Thanks.
EDIT: Extra Code added
void ConfigureDatagrid()
{
datagrid.Resize += new EventHandler(datagrid_Resize);
panel4.Controls.Remove(datagrid);
panel4.Invalidate();
datagrid.Location = new System.Drawing.Point(0, 40);
panel4.Controls.Add(datagrid);
columnsWidth = datagrid.Columns.GetColumnsWidth(DataGridViewElementStates.Visible);
checkDatagridControls();
datagrid.ScrollBars = ScrollBars.Both;
datagrid.Anchor = (AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right);
datagrid.Dock = (DockStyle.Top);
AdjustDatagridHeight();
AdjustDatagridWidth();
datagrid.RowHeadersVisible = false;
datagrid.AutoResizeColumnHeadersHeight();
}
The code above is called once a new datagrid has been obtained as such:
datagrid = file.returnDatagrid(mouse, experiment);
ConfigureDatagrid();
The panel is passed through from the Winform into the datagrid class.
Your code is not complete. What do "datagrid" refer to exactly and how is it initiated/disposed ? in your event ? Then why don't you handle removal/adding there ?
panel4.Controls.Remove(datagrid);
panel4.Controls.Add(datagrid);
What you are basically doing here is just removing the element and then adding it back again. You should call the first line before your event, and you're done I think.
Besides, I think you are not doing things properly : Why Remove/Add your DGV anyway and replace it by the same components. It should NOT be this way. since it appears that you are handling the same type of data, then you should affect the DataTable only whithout touching the DataGridView
EDIT :
According to your edit and comments, this should make more sense :
panel4.Controls.Remove(datagrid);
datagrid=file.returnDatagrid();
panel4.Controls.Add(datagrid);
panel4.Invalidate();
You're removing and readding the same datagrid
:
panel4.Controls.Remove(datagrid);
panel4.Invalidate();
datagrid.Location = new System.Drawing.Point(0, 40);
panel4.Controls.Add(datagrid);
nowhere in this code do you update datagrid
so you are trying to remove something that doesn't exist in Controls
and then adding it.
You need to get your old datagrid
to pass to Remove
or remove it before update the variable:
panel4.Controls.Remove(datagrid);
datagrid=file.returnDatagrid();
datagrid.Location = new System.Drawing.Point(0, 40);
panel4.Controls.Add(datagrid);
panel4.Invalidate();
精彩评论