Mallory Rich Mallory Rich - 1 month ago 7
C# Question

Reading from ListBox Line by line

I am creating a program where the user is pressing buttons like move 10 and move 1 to move a robot and when a user presses the button it will add a text in a listbox like "MoveRobot1" so when the user has finished pressing the buttons and presses the Play button, the program should go down the list line by line moving the robot based on the list at an interval of 300ms but I don't understand how to make it read line by line instead of all at once when I press Play.

private void BtnPlay_Click(object sender, EventArgs e)
{
this.WorkProgress += new WorkProgressHandler(DoWork);
_counter = 0;

this.robot.Reset();
this.MoveRobot(0);
string query1 = "MoveRobot(1)";
string query2 = "MoveRobot(10)";
for (int i = 0; i < MoveBox.Items.Count; i++)
{
if (MoveBox.Items[i].ToString() == query1)
{
this.MoveRobot(1);
DoWork();

}
if (MoveBox.Items[i].ToString() == query2)
{
this.MoveRobot(10);
DoWork();
}
}
}

private void DoWork()
{
_counter++; // increment the counter
}

Answer

Use Thread.Sleep in the end of every iteration :

for (int i = 0; i < MoveBox.Items.Count; i++)
{
    if (MoveBox.Items[i].ToString() == query1)
    {
        this.MoveRobot(1);
        DoWork();
    }
    if (MoveBox.Items[i].ToString() == query2)
    {
        this.MoveRobot(10);
        DoWork();
    }
    Thread.Sleep(300);
}
Comments