C# winform中的面板行为错误

C# winform中的面板行为错误,c#,winforms,panel,C#,Winforms,Panel,我在Winforms中有一个面板,在方法调用期间加载其中的面板。 在方法调用中,我编写了以下代码: //to get number of panel present in main panel so that new panel position can be set int counT = panel1.Controls.Count; Panel p = new Panel(); p.Location = new Point(3, 3 + (counT * 197)); p.Size = n

我在Winforms中有一个面板,在方法调用期间加载其中的面板。 在方法调用中,我编写了以下代码:

//to get number of panel present in main panel so that new panel position can be set
int counT = panel1.Controls.Count;

Panel p = new Panel();
p.Location = new Point(3, 3 + (counT * 197));
p.Size = new Size(280, 150);

//To add panel to parent panel
panel1.Controls.Add(p);
每次调用该方法时,它都会在主面板中加载一个面板。如果我不滚动滚动条,一切正常。一旦我将滚动条向下滚动,然后调用该方法,面板之间的距离就会增加

根据写入的逻辑,两个面板之间的距离沿Y轴应为197像素,但它正在增加更多

我已经设置了
AutoScroll=true


任何帮助

这是一种非常奇怪的行为,直到现在我才知道(而且我在WF方面有很多经验)。在执行上述代码时,当父面板滚动时可以看到。我原以为子控件的位置是相对于
ClientRectangle
,但事实证明它们是在计算
DisplayRectangle

很快,而不是这个

p.Location = new Point(3, 3 + (counT * 197));
用这个

var parentRect = panel1.DisplayRectangle;
p.Location = new Point(parentRect.X + 3, parentRect.Y + 3 + (counT * 197));  

面板。AutoScrollPosition
影响所有子控件的
位置
属性。滚动就是这样工作的。所以您应该记住,例如,您可以存储当前滚动位置,将位置移动到(0,0),添加新控件,然后恢复滚动位置

//to get number of panel present in main panel so that new panel position can be set
int counT = panel1.Controls.Count;
var pos = this.panel1.AutoScrollPosition; // Whe are storing scroll position
this.panel1.AutoScrollPosition = new Point(Size.Empty);
Panel p = new Panel();
p.Location = new Point(3, 3 + (counT * 197));
p.Size = new Size(280, 150);
p.BorderStyle = BorderStyle.FixedSingle;


//To add panel to parent panel
panel1.Controls.Add(p);
this.panel1.AutoScrollPosition = new Point(Math.Abs(pos.X), Math.Abs(pos.Y)); // We are restoring scroll position

您的代码将每个新面板的位置设置为上一个面板位置的197px偏移量。它没有将两个面板之间的间距设置为197px…为什么不将边距设置为197px?感谢大家的建议…我没有使用面板,而是尝试使用FlatLayoutPanel,效果很好…无需设置内部面板位置&全部。。。