2012-07-19 105 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; 
    } 
    } 
}