Jorge Jorge - 9 months ago 50
C# Question

Fix Anchoring when changing parent

I have a RichTextBox, a Button and a List Box with Anchor set to Top, Bottom, Right.
Whenever I change the form size and then change their parent (from one tab of a TabControl to another) their position gets messed up.,FyFIQTL,7K7HMTt,Nqrm20y

First image: Before re-size ✓

Second image: After re-size ✓

Third image: After re-size on different tab ✖

Fourth image: Switched back to original tab ✖

This is the code i use to change the parent:

private void tabTabs_Selected(object sender, TabControlEventArgs e)
if (tabTabs.SelectedTab == tabChat || tabTabs.SelectedTab == tabCmd)
lstUsers.Parent = tabTabs.TabPages[tabTabs.SelectedIndex];
rtbSend.Parent = tabTabs.TabPages[tabTabs.SelectedIndex];
btnSend.Parent = tabTabs.TabPages[tabTabs.SelectedIndex];

Answer Source

This is a fairly unusual way to do a user interface. Not that it's necessarily wrong, but I think you're encountering one of the many potential difficulties that this design creates.

The main problem is that you are reusing user interface elements for different functions. A chat box becomes a command box on a different tab, a "send" button will send chat messages on one tab and commands on another tab, etc. Every time you switch tabs, you'll have to be extremely careful to do a lot of house cleaning and do it correctly. It just sounds overly complex.

Most user interfaces would be designed using multiple text boxes, buttons, etc., one for each tab. Each text box or button would serve one single purpose. If you need several different elements to look and behave similarly, you can use styles, templates, or create your own UserControls to help facilitate that.

The exception to that rule would be your viewer list. It looks as if that always stays the same regardless of what tab you're on. If it were me, I'd only have one instance of the viewer list, but I wouldn't put that in the tab control. I'd just place it next to the tab control so you can always see it.