Search code examples
c#winformsautoscroll

Panel AutoScrollPosition leaves white spaces between elements


Can some one explain why the code below leaves white spaces between inserted elements and how to fix it?

enter image description here

private void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
    {
        if (outLine.Data != null && !String.IsNullOrWhiteSpace(outLine.Data))
        {
            this.lineCount++;
            Label TestLBL = new Label();
            TestLBL.Text = outLine.Data.TrimStart();
            TestLBL.Name = this.lineCount.ToString();
            TestLBL.AutoSize = true;
            TestLBL.Location = new Point(10, panel1.Controls.Count * 20);

            BeginInvoke(new MethodInvoker(() =>
            {
                panel1.Controls.Add(TestLBL);
                panel1.AutoScrollPosition = new Point(10, this.lineCount * 20);


            }));
        }
    }

Solution

  • Since you aren't using a FlowLayoutPanel, you would have to compensate for the scrollbar position in order to get the correct location:

    TestLBL.Location = new Point(10, panel1.AutoScrollPosition.Y + panel1.Controls.Count * 20);
    

    You should probably put all of that GUI control creation code inside that BeginInvoke block. GUI controls like to be created on the GUI thread.