C# 遍历我的Datagridview

C# 遍历我的Datagridview,c#,datagridview,filter,iteration,C#,Datagridview,Filter,Iteration,我正在尝试为我的DataGridView做一个文本过滤器 当我的文本框中的文本发生变化时,我试图使所有不匹配的行都不可见。但在我更改文本框中的文本后,我的迭代循环不断告诉我“WindowsFormsApplication1.exe中发生了类型为'System.NullReferenceException'的未处理异常” 这是我的Datagridview代码: private void Icon_Picker_Load(object sender, EventArgs e) {

我正在尝试为我的DataGridView做一个文本过滤器

当我的文本框中的文本发生变化时,我试图使所有不匹配的行都不可见。但在我更改文本框中的文本后,我的迭代循环不断告诉我“WindowsFormsApplication1.exe中发生了类型为'System.NullReferenceException'的未处理异常”

这是我的Datagridview代码:

    private void Icon_Picker_Load(object sender, EventArgs e)
    {
    //    string[] first = {"0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17"};

        int j = 0;
        //image directory
        DirectoryInfo dir = new DirectoryInfo(imagepath);

        //getting all files from the Directory
        foreach(FileInfo file in dir.GetFiles())
        {

            try
            {
                this.img16x16.Images.Add(Image.FromFile(file.FullName));
                this.img32x32.Images.Add(Image.FromFile(file.FullName));


                while (j < img16x16.Images.Count)
                {
                    var row = new DataGridViewRow();

                    dataGridView1.Rows.Add(row);
                    dataGridView1.Rows[j].Cells[0].Value = file.Name;

                    //Resizing icons to 16x16 icons
                    img16x16.ImageSize = new Size(16, 16);

                    //adding icons to the datagridview
                    dataGridView1.Rows[j].Cells[1].Value = img16x16.Images[j];

                    //Resizing icons to 32x32 icons
                    img32x32.ImageSize = new Size(32, 32);

                    //adding icons to the datagridview
                    dataGridView1.Rows[j].Cells[2].Value = img32x32.Images[j];
                    j++;

                }

            }catch
            {
                Console.WriteLine("This is not an image file");
            }
        }          
    }

您应该检查单元格中的空值

foreach (DataGridViewRow row in dataGridView1.Rows)
    {
     if(row.Cells[0].Value!=null)
      {
      //code
      }
    }

更多信息,您应该检查dataGridView1.Rows.Count是否也不应等于零。

哪一行引发异常?如果(!row.Cells[0].Value.ToString().Contains(txtFilter.Text)),则该单元格为空。一定要检查这个!
foreach (DataGridViewRow row in dataGridView1.Rows)
    {
     if(row.Cells[0].Value!=null)
      {
      //code
      }
    }