Search code examples
c#winformslayouttabstabcontrol

How to avoid image overlapping the text of TabPage in WinForms after setting it programatically?


I have a Windows Forms application with a TabControl that has two TabPage objects:

Tab pages in their default state

What I am aming for is a way to display an icon beside the titles of the tabs. For that, an ImageList is assigned to the TabControl so the ImageIndex property of the tab pages can be set. When I do that in the designer, it looks fine, but when changing it programatically in my code like this:

myTabControl.TabPages[0].ImageIndex = 0

, it has this weird overlapping effect:

Tab pages when edited programatically

How can I avoid this? Things I've tried are myTabControl.PerformLayout() and myTabControl.Invalidate(), but none of them worked. Thanks!


Solution

  • So apparently, there is a workaround solution:

    myTabControl.ItemSize = myTabControl.ItemSize;
    

    This only works if the SizeMode of the tab control is set to TabSizeMode.fixed. Thanks to Dr.Null (comment above) to point this out.

    While this is simple though, it's not so elegant and confuses readers. I wonder whether there are other, intended solutions or whether this is a "hole" in WinForms Microsoft didn't consider.