2012-07-19 52 views
1

我試圖找到每個DatagridviewImageCell並將其屬性ImageLayout設置爲DataGridViewImageCellLayout.Zoom,以便該單元格中的圖像將被縮放。我正在使用此代碼,但出現錯誤:Unable to cast object of type 'System.Windows.Forms.DataGridViewRow' to type 'System.Windows.Forms.DataGridViewImageCell'.此處:(DataGridViewImageCell Imgrow in dataGridView1.Rows。這是我正在使用的代碼。在C#中查找datagridview單元格類型?

    foreach (DataGridViewImageCell Imgrow in dataGridView1.Rows) 
       {      
        if (dataGridView1.Rows[a].Cells[1].Value == "Image") 
        { 
         Imgrow.ImageLayout = DataGridViewImageCellLayout.Zoom; 
        } 
       } 

我該如何解決?此外,該列是一個texbox列,但我用它來替換單元格。

int a = 0; 
dataGridView1.Rows.Insert(0, 1); 
dataGridView1.Rows[a].Cells["Column1"] = new DataGridViewImageCell(); 
dataGridView1.Rows[a].Cells["Column1"].Value = picturebox1.Image; 

回答

3

您需要使用行對象遍歷行,然後使用單元對象遍歷單元格。

事情是這樣的:

foreach (DataGridViewRow dr in dataGridView1.Rows) { 
    foreach (DataGridViewCell dc in dr.Cells) { 
    if (dc.GetType() == typeof(DataGridViewImageCell)) { 
     ((DataGridViewImageCell)dc).ImageLayout = DataGridViewImageCellLayout.Zoom; 
    } 
    } 
}