2015-08-19 57 views
1

我試圖得到一些數據到我的DataGridView有一個for循環添加塞進一個GridView與一個for循環

但事情是,我的環跳了出來,如果我的櫃檯在2無原因,我不知道爲什麼

這是我的代碼:

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); 

感謝您的幫助

編輯:我找到了解決辦法,我不得不把這些2:

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

在裏面的for循環

+1

首先,你的循環會在最後得到一個異常。 <=計數應該是<計數 –

+0

哦,是的,謝謝我沒有注意到 –

回答

0

我的代碼前面看起來你已經混了你的行變量和DataGrid的行。

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); 
} 

在你的版本你直接寫入到網格,沒有任何參照其大小,我猜它是一個或兩排大的,你有一些其他的設置,你想外面寫的界限。

+0

感謝您的幫助,我找到了解決方案,並將其編輯到我的主題:) –

+0

@DanielHalling如果我的答案導致解決方案,可以標記它作爲接受的答案? – DUBYATOO