简体   繁体   中英

C# WinForm TabControl Formatting Issue

When programmatically adding controls to a tab control, I have been using the Form_Load event to create and embed things like datagridviews into my UI. I made a class that inherits from DataGridView

class DBDataGridView : DataGridView
{
    public DBDataGridView()
    {
        DoubleBuffered = true;
        AllowUserToAddRows = false;
        AllowUserToDeleteRows = false;
        AllowUserToResizeRows = false;
        AllowUserToOrderColumns = false;
        AllowUserToResizeColumns = false;
        RowHeadersVisible = false;
        AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
        ReadOnly = true;
        Dock = DockStyle.Fill;
        SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        TabStop = false;
    }
}

And I call it later in the Form_Load event like so

    private void MainDesignerForm_Load(object sender, EventArgs e)
    {
        DBDataGridView _DGV = new DBDataGridView();

        var listOfOverlays = new List<OverlaySelectionList>()
        {
            new OverlaySelectionList { Description = "Description 1", PartNumber = "123-R1"},
            new OverlaySelectionList { Description = "Description 2", PartNumber = "456-R1"}
        };
        var overlayList = new BindingList<OverlaySelectionList>(listOfOverlays);
        _DGV.DataSource = overlayList;
        Tab_Overlay.Controls.Add(_DGV);
        _DGV.ClearSelection();
    }

This gridview is on the THIRD tab of the TabControl, and everything works as expected except the ClearSelection(). No matter where I call it, it does not clear the initial row selection of the DGV. However, if I fire the same code block from a button ON the third tab, the formatting AND the ClearSelection() behave as expected.

What is causing this behavior?

Thanks to 41686d6564 and Jimi for the insight into the specifics on why this was happening.

Reiterating what they said in the comments: Assignment of properties appear to be cached regardless of whether the control they belong to is active or not (Hence why all the sizing and formatting properties were present at run time). However, actions that require a handle, like ClearSelection() require the control to be shown and active for the intended behavior to be observed.

Setting the selected tab to where the DataGridView before calling ClearSelection() was the solution (Or in my case, I had nested tabs, so I had to follow the tab tree to get to the specific tab that the DataGridView was on)

So now, part of the Load_Form logic is to check WHERE the control is located, make that tab active, THEN format and clear selections for each control that is being added. This allowed ClearSelection() to work as intended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM