简体   繁体   中英

Index was out of range. Must be non-negative and less than the size of the collection error

hi i am getting this error when running this piece of code and cant figure it out. cheers:

      DataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        try
        {
            for (int i = 0; i <= (DataGridView1.Rows.Count); i++)
            {

                if (DataGridView1.Rows[i].Cells[2].ToString().Equals(returnID))
                {
                   SignIn_Time(updateCmd, OLEDB_Connection, varName, varID, varTime);
                   break;
                }
            }
        }
        catch
        {

由于从零开始的索引,它应该小于计数,而不是等于:

i < DataGridView1.Rows.Count

The error is clear on what's going on:

[index] non-negative and less than the size of the collection.

Replace <= with < in the loop header:

for (int i = 0; i < (DataGridView1.Rows.Count); i++) {
    ...
}

In addition, you need to make sure that each row has at least three cells, because you are accessing the third cell in a row: Cells[2]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM