遍历我的 Datagridview

Iterating through my Datagridview

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

当我的文本框中的文本发生变化时,我试图使所有不匹配的行不可见。但是在我更改文本框中的文本后,我的迭代循环不断告诉我 "An unhandled exception of type 'System.NullReferenceException' occurred in WindowsFormsApplication1.exe"

这是我的 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.ToString().Contains(txtFilter.Text))
            {
                row.Visible = false;

            }
            else 
            {

                row.Visible = true;
            }

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

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

此外,您应该检查 dataGridView1.Rows.Count 也不应等于零。