C# Winforms TabControl elements reading as empty until TabPage selected

Deadly 提交于 2019-12-06 11:12:30
Geo Ego

ho is correct; the elements on a TabPage are not created until that TabPage is selected. I just added a loop upon form load that selects each TabPage and now it works fine.

foreach (TabPage tp in tabControl1.TabPages)
{
    tp.Show();
}

I'm not sure if you can. The following is a quote from MSDN:

"Controls contained in a TabPage are not created until the tab page is shown, and any data bindings in these controls are not activated until the tab page is shown."

However, instead of having the update code get the values from the controls directly, maybe you could create a class that could hold that DataTable you use to populate the controls and then when the update code is called it asks the class for the value and the class checks if the control is loaded and otherwise it gets the value from the DataTable instead.

The issue is that the controls are not Created until the tab is displayed. One solution would be to actually create the controls on loading the page like so:

private static void CreateControls( Control control )
{
    CreateControl( control );
    foreach ( Control subcontrol in control.Controls )
    {
        CreateControl( subcontrol );
    }
}
private static void CreateControl( Control control )
{
    var method = control.GetType().GetMethod( "CreateControl", BindingFlags.Instance | BindingFlags.NonPublic );
    var parameters = method.GetParameters();
    method.Invoke( control, new object[] { true } );
}

Then in the constructor on your form, you'd do something like:

public Form()
{
    CreateControls( this.tabPage1 );
}

This solution relies on the fact that there is an internal CreateControls method takes a single boolean parameter which will let you create the control even if it is not visible.

My workaround for this issue was to add the following code to the form load event;

this.tabcontrol1.BindingContext = this.BindingContext;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!