索引超出了c#的范围

本文关键字:范围 索引 | 更新日期: 2023-09-27 18:12:51

我试着调试这个代码,但我不能如何修复它。如果我使用这段代码,我的WF运行:

try 
{                       
    rtxttdwhat.Text = dataGridView1.CurrentRow.Cells[8].Value.ToString();
    lbtdtime1.Text = dataGridView1.CurrentRow.Cells[1].Value.ToString() +
            ":" + dataGridView1.CurrentRow.Cells[0].Value.ToString();

另一个是show INDEX OUT OF RANGE:

int a, b;
a = 1;
b = a+1;
try 
{
    if (int.Parse(dataGridView1.Rows[a].Cells[1].Value.ToString()) == int.Parse(lbhour.Text) &&             
        int.Parse(dataGridView1.Rows[a].Cells[0].Value.ToString()) == int.Parse(lbmin.Text))
    {
        a = a + 1;
        b = a + 1;
    }
    rtxttdwhat.Text = dataGridView1.Rows[a].Cells[8].Value.ToString();
    lbtdtime1.Text = dataGridView1.Rows[a].Cells[1].Value.ToString() + 
            ":" + dataGridView1.Rows[a].Cells[0].Value.ToString();

索引超出了c#的范围

我不是100%确定你在做什么,特别是与b ?但是你可以试试这个:

int RowCount = dataGridView1.Rows.Count;
if(a <= RowCount)
{
     //Youre Code
}
else
{
    //Out of Range
}

嗨,这个链接可能对你有用IndexOutOfRangeException

修改代码并在访问它们之前先检查行和单元格计数。