1

I'm trying to get some Data into my Datagridview with a For-Loop

But the thing is, my Loop jumps out if my counter is at 2 for no reason and I dont know why

This is my Code:

var row = new DataGridViewRow();
//image directory
DirectoryInfo dir = new DirectoryInfo(@"C:\Users\Daniel\Pictures");

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

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

    }catch
    {
         Console.WriteLine("This is not an image file");
    }
}
for (int j = 0; j <= this.img16x16.Images.Count; j++)
{

    dataGridView1.Rows[j].Cells[0].Value = img16x16.Images[j].ToString();
    img16x16.ImageSize = new Size(16, 16);
    dataGridView1.Rows[j].Cells[1].Value = img16x16.Images[j];
    dataGridView1.Rows.Add(row);

Thanks for your help

edit: I found the solution, i just had to put these 2:

var row = new DataGridViewRow();
dataGridView1.Rows.Add(row);

in front of my code inside the for-loop

2
  • 1
    For one thing, your loop will get an exception at the end. <= count should be < count Commented Aug 19, 2015 at 19:54
  • Oh yeah, thank you I didn't noticed Commented Aug 19, 2015 at 20:09

1 Answer 1

1

Looks like you've mixed up your row variable and the datagrid's rows.

for(int j = 0;  j < this.img16x16.Images.Count; j++)
{
    row = new DataGridViewRow();
    //Add first cell and its data to the variable "row"
    //Size changes
    //Add second cell and its data to the variable "row"

    //Add "row" to the grid:
    dataGridView1.Rows.Add(row);
}

In your version you were writing straight to the grid without any reference to its size, and I'm guessing it was one or two rows large by some other settings you have, and you tried to write outside its bounds.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help, i found the solution and edited it into my Thread :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.