Search code examples
c#winformslistboxsendkeys

InvalidArgument=Value of '2' is not valid for 'index'. When trying to type characters individually


I'm trying to type a string with small spaces between each character.

Then I use this I'm getting an error: InvalidArgument=Value of '2' is not valid for 'index'. in line: if (currentChar == lbMessage.Items[tickCount].ToString().Length) I did similar with text box but I can't do it for ListBox.

private void Space(object sender, EventArgs e)
{
    if (tickCount < lbMessage.Items.Count)
    {
        SendKeys.Send(lbMessage.Items[tickCount].ToString().Substring(currentChar++, 0));
        tickCount++;

        if (currentChar == lbMessage.Items[tickCount].ToString().Length)
        {
            tmrSpace.Enabled = false;
            SendKeys.Send("{enter}");
        }

        if (tickCount >= lbMessage.Items.Count) tickCount = 0;
    }

    tmrSpace.Interval = random.Next(50, 100);
}

This works for a textbox field:

private void Space(object sender, EventArgs e)
{
    SendKeys.Send(txtText.Text.Substring(b++, 1));

    tmrSpace.Interval = random.Next(50, 150);

    if (b == txtText.TextLength)
    {
        tmrSpace.Enabled = false;
        SendKeys.Send("{enter}");
    }
}

Solution

  • Look at this:

    if (tickCount < lbMessage.Items.Count)
    {
        SendKeys.Send(lbMessage.Items[tickCount] // etc, irrelevant
        tickCount++;
    
        if (currentChar == lbMessage.Items[tickCount].ToString().Length)
    

    Now suppose that tickCount is exactly lbMessage.Items.Count - 1. The first time you index into it that's fine - but then you increment tickCount and index again, at which point tickCount will equal lbMessage.Items.Count, and you'll get that exception.

    Your code isn't particularly clear to me (I'm tired) but you may well want to move the increment of tickCount to later in the code...