Search code examples
c#winforms.net-4.5datagridviewcolumndatagridviewimagecolumn

Change the type of a DataGridViewColumn using AutoGenerateColumns


I have a query using a dynamic pivot table which will return me a different number of columns to bind to my DataGridView. I am using AutoGenerateColumns = true...which is the only way to display the pivot columns. How can I programmatically make some of these columns of type DataGridViewImageColumn? Everything is automatically a DataGridViewTextBoxColumn when using AutoGenerateColumns. I can't create these columns programmatically (see below) because I do not know how many columns will be returned or what the Column names will be.

DataGridViewColumn col = new DataGridViewImageColumn()
col.Name = ...
col.DataPropertyName = ...
DataGridView.Columns.Add(col)

As it's being created, I would need something like this:

DataGridView1.Columns[10].Type = DataGridViewImageColumn

...but I know this doesn't exist. Thanks


Solution

  • If you are using AutoGenerateColumns then you can't change their types after binding the source. You would have to remove the column then add it back:

            DataTable dt = new DataTable();
            dataGridView1.DataSource = dt;
    
            DataGridViewImageColumn imageCol = new DataGridViewImageColumn();
            imageCol.Name = "target_column";
            imageCol.DisplayIndex = dataGridView1.Columns["source_column"].DisplayIndex + 1;
    
            dataGridView1.Columns.Add(imageCol);
    
            for(int index = 0; index < dt.Rows.Count; index ++)
            {
                dataGridView1.Rows[index].Cells["target_column"].Value = dt.Rows[index]["source_column"];
            }
    
            dt.Columns.Remove("source_column");
    

    EDIT:

    If you can't use column names, you could try checking the type of data present in the column. But this solution would have issues if your columns contained mixed types, and you would need to check whether the datasource contained data before using it:

    foreach (DataGridViewColumn column in dataGridView1.Columns)
    {
       if (dataGridView1.Rows[0].Cells[column.Name].Value.GetType() == typeof(System.Drawing.Bitmap)) //Or whatever type you store your image as
       {
          //Do the copy over
       }
    }