0

I have a multiline textbox and when I replace its text, the scroll bar goes to top ...

How can I prevent that and keep the scrollbar at the bottom like AppendText method in textbox?

My code is as follows:

int milisecond = 100;
int persent = 0;
do
{
    Random rnd = new Random();
    int add = rnd.Next(1, 9);
    int wait = rnd.Next(50, 1000);
    textBox1.Text = textBox1.Text.Replace("Progress %" + persent, "");
    persent += add;
    if (persent > 100)
    {
        persent = 100;
    }

    textbox1.AppendText("Progress %" + persent);
    Task.Delay(milisecond).Wait();

    this.Refresh();

} while (persent != 100);
ne1410s
  • 6,864
  • 6
  • 55
  • 61
Al00X
  • 1,492
  • 1
  • 12
  • 17
  • I *knew* that's how progress bars worked! :oP Out of interest, is this a windows forms application? – ne1410s Jan 08 '16 at 13:04
  • Windows Form , But Like Console Application :P ... – Al00X Jan 08 '16 at 13:05
  • 1
    From what I can tell, the code is possibly executing on the same thread as the UI. Therefore you are trying to force the screen to update by using the `Refresh()` method. I would suggest using `BackgroundWorker` to assist you in thread management for code / UI tasks. It is explained here: http://www.dotnetperls.com/backgroundworker – ne1410s Jan 08 '16 at 13:14
  • Oh Thanks ! , I Removed this.Refresh() and worked :D , Thanks Again – Al00X Jan 08 '16 at 13:17
  • 1
    No problem - If if the future you wish to run code and update the UI simultaneously (which is the point of progress indicator, I think) then I would strongly recommend BackgroundWorker - its a very handy way to manage this type of threading consideration. – ne1410s Jan 08 '16 at 13:19
  • Actually, `BackgroundWorker` has largely been superseded by `Task`, `await` and `IProgress`. [See this blog from Mr Cleary](http://blog.stephencleary.com/2012/02/reporting-progress-from-async-tasks.html) – Matthew Watson Jan 08 '16 at 13:39

1 Answers1

0

add this after the AppendText()

        textbox1.ScrollToCaret();
FonnParr
  • 325
  • 1
  • 7
  • Glitches the program ! , Scrollbar goes to top and then goes to down and again ... – Al00X Jan 08 '16 at 13:24
  • That's a separate issue - look here http://stackoverflow.com/questions/1550293/stopping-textbox-flicker-during-update – FonnParr Jan 08 '16 at 13:38