在datagridview中,我使用for循环将值存储在右行.它显示索引超出范围错误

本文关键字:显示 索引 错误 范围 存储 datagridview 循环 for | 更新日期: 2023-09-27 18:06:18

foreach (DataRow row in table.Rows)
{                    
   if (row["ProductId"].ToString().Contains(searchValue))
   {
       for (int i = 1; i <= table.Rows.Count; i++)
       {                            
            MessageBox.Show("Product Id: " + row["ProductId"].ToString());
            MessageBox.Show(dataGridView1.Rows.Count.ToString());
            dataGridView1.Rows[i].Cells[0].Value = row["ProductId"].ToString();
            dataGridView1.Rows[i].Cells[1].Value = row["ProductName"].ToString();
            dataGridView1.Rows[i].Cells[2].Value = row["ProductType"].ToString();
            dataGridView1.Rows[i].Cells[3].Value = row["CreateDate"].ToString();
            dataGridView1.Rows[i].Cells[4].Value = row["UpdateDate"].ToString();
            dataGridView1.Rows[i].Cells[5].Value = row["IsActive"].ToString();
       }
   }
} 

我正在使用一个datagridview;我使用for循环来存储行值,但我得到以下错误:

索引超出范围

我怎么解决它?

在datagridview中,我使用for循环将值存储在右行.它显示索引超出范围错误

我想你

int i = 1; i <= table.Rows.Count
应该

int i = 0; i < table.Rows.Count

因为您的行索引从0开始并保持到table.Rows.Count - 1,这就是为什么您没有索引为Rows[table.Rows.Count],最后索引将是Rows[table.Rows.Count - 1]

下次,请调试你的代码并检查你的datagridview是否有索引。

相关;

  • 什么是IndexOutOfRangeException/ArgumentOutOfRangeException,我如何修复它?