Why in Visual C# .NET in WinForm, tabPage1 will not update control content changes unless tabPage1 is selected?

574 views Asked by At

So in a basic WinForm in Visual C# .NET I have tabControl1 with two pages: tabPage1 and tabPage2.

Let's say i have label1 in tabPage1, and a timer which updates every 10 seconds and changes the label1 to the current time:

private void timer1_Tick(object sender, EventArgs e)
{
    button1.PerformClick();
}
private void button1_Click(object sender, EventArgs e)
{
     label1.Text = "Last updated: " + DateTime.Now.ToString() + "(local time)";
}

Now, if I have tabPage1 selected, the label1.Text updates just fine, even if i have the application minimized. However, if tabPage2 is selected, then label1.Text never updates until I select the tabPage1 which contains the label1.

Since in my application I have multiple tabs, which need to update content from the internet and populate labels and listviews, I need it to be able to update content on the tabs without me selecting.

How would I go about doing this, without programmatically forcing the user to select the tab to update content, which would disturb the user if they were using a different tab?

Note: I am trying to avoid this cludgy solution (which does work, but is very annoying to the user):

private void timer1_Tick(object sender, EventArgs e)
{
    int x = tabControl1.SelectedIndex;
    if (tabControl1.SelectedIndex != 0)
    {
        tabControl1.SelectedIndex = 0;
        label1.Text = "Last updated: " + DateTime.Now.ToString() + "(local time)";
        tabControl1.SelectedIndex = x;
    }
}

Edit: I have tried tabPage1.Update(); and it does not work, still does not update the time so when I select tabPage1 after it should have updated a couple times, it shows the same time as before.

Edit2: I left out information critical to the problem. in timer1 I was doing: button1.PerformClick(); However, PerformClick(); will not work if the button is hidden. So when I'm in tabPage2 it is not properly clicking the button because the button is hidden in tabPage1. So the solution is to take the button code, put it into a method, and instead use the timer to do the method rather than PerformClick(), then all works fine no matter you are in tabPage1 or not.

2

There are 2 answers

5
Matheus Rocha On

Along with the code that makes the changes, try calling tabPage1.Update(). Maybe it is not updating because it isn't visible. Either way, when the user changes to the tab to see its content it will probably call the method above and display its content updated. So it's not really necessary to update it if it is in the background. I cannot test it myself as I no longer have visual studio :(

0
KingofGreenland On

See the edit in the question, the reason it wasn't working was because i used button.PerformClick() not a normal method call.