The position position of the control does not seem to work when the scroll moves (C #, winforms)

Description of the problem:

  • Create a "custom control." Set the AutoScroll property to true. Change the color of bg to green.
  • Create a second "user control". Change the color of bg to red.
  • On the main form, place the first user control
  • In the code, create 20 instances of the second control
  • Add a button and to a button:
    • The code sets their position in the loop, as c.Location = new Point (0, y);
    • y + = c.Height;
  • Launch the application.
  • Press button
  • Scroll container
  • Press the button again, and someone, please explain to me WHY 0 is not the beginning of the container form ?! Controls Offset ...

Before answering:

1) Yes, everything should be so.

2) Sample code below:

public partial class Form1 : Form { List<UserControl2> list; public Form1() { InitializeComponent(); list = new List<UserControl2>(); for (int i = 0; i < 20; i++) { UserControl2 c = new UserControl2(); list.Add(c); } } private void Form1_Load(object sender, EventArgs e) { foreach (UserControl2 c in list) userControl11.Controls.Add(c); } private void button1_Click(object sender, EventArgs e) { int y = 0; foreach (UserControl2 c in list) { c.Location = new Point(0, y); y += c.Height; } } } 
+4
source share
2 answers

Because Location gives the coordinates of the upper left corner of the control relative to the upper left corner of its container. Therefore, when scrolling down, the location will change.

Here's how to fix it:

  private void button1_Click(object sender, EventArgs e) { int y = list[0].Location.Y; foreach (UserControl2 c in list) { c.Location = new Point(0, y); y += c.Height; } } 
+6
source

The first element will not be at position 0, because at the time of calculating the location, the new element is not added to the panel elements. In addition, you should use AutoScrollPosition to align positions. Here is my suggestion:

  int pos = (Container.AutoScrollPosition.Y != 0 ? Container.AutoScrollPosition.Y - newitem.Height : 0); if (Container.Controls.Count > 0) { foreach (Control c in Container.Controls) { c.Location = new Point(0, pos); pos += c.Height; } } } newitem.Location = new Point(0, pos); Container.Controls.Add(newitem); 
0
source

Source: https://habr.com/ru/post/1302079/


All Articles