3

I get the following error:

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in System.Windows.Forms.dll

Additional information: InvalidArgument=Value of '1' is not valid for 'index'

For the following code.

private void button_confirm_Click(object sender, EventArgs e)
    {
        listBox_savedata.Items.Add(textBox_ordertostart.Text +" "+ comboBox_suburb.SelectedItem.ToString() + " " + dateTimePicker2.Value.ToShortDateString());
     
        
            for (int i = 0; i <= listBox_savedata.Items.Count; i++)
            {
                string s1 = listBox_savedata.Items[i].ToString();
                int startpos = s1.IndexOf("PM");
                string sub = s1.Substring(0, 5);
                if(sub+" "+"PM"==DateTime.Now.ToString("HH:mm tt"))
                    { 
                    mplayer.PlayLooping();
                
            }
        }
    }
Community
  • 1
  • 1
zia khan
  • 361
  • 3
  • 14

2 Answers2

2

Change your for loop:

old:

for (int i = 0; i <= listBox_savedata.Items.Count; i++) // <=

new:

for (int i = 0; i < listBox_savedata.Items.Count; i++) // <
Roman
  • 11,966
  • 10
  • 38
  • 47
1

This line is wrong:

for (int i = 0; i <= listBox_savedata.Items.Count; i++)

Arrays in C# are zero indexed, so the last index in the array is one less than the count. Change it to:

for (int i = 0; i < listBox_savedata.Items.Count; i++)

and all will be fine.

Alternatively use a foreach loop:

foreach (var item in listBox.savedata.Items)
{
     int startpos = item.IndexOf("PM");
     string sub = item.Substring(0, 5);
     ....
}
ChrisF
  • 134,786
  • 31
  • 255
  • 325