Hunter Mitchell
Hunter Mitchell

Reputation: 7293

Finding datagridview cell type in C#?

i am trying to find each DatagridviewImageCell and set its property ImageLayout to DataGridViewImageCellLayout.Zoom so the image in that cell will be zoomed. I am using this code, but am getting an error: Unable to cast object of type 'System.Windows.Forms.DataGridViewRow' to type 'System.Windows.Forms.DataGridViewImageCell'. here: (DataGridViewImageCell Imgrow in dataGridView1.Rows. This is the code i am using.

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

How do i fix it? Also, the column is a texbox column, but i am using this to replace the cell.

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

Upvotes: 1

Views: 13468

Answers (1)

LarsTech
LarsTech

Reputation: 81655

You need to loop over the rows with a row object, and then loop over the cells with a cell object.

Something like this:

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

Upvotes: 3

Related Questions