Add image column dyanamically to gridview in C# desktop application.


Some times you may need to add image columns to your grid view add add multiple images
for various column cells.

This code is developed by my self and my grid was to display about details of various types of files.
Also I needed to show a image thumbinail column as the file type of the row.Therefore I have to get the
data row of a  data bind table and check the file type and then select the image and bind it to image column cell. Finally add the data row to grid view.

To do this I have used the "CellFormatting" function of the gridview and below show the images
column configuration of the gridview.



Then this is CellFormatting fucntion at my code behind.


//Start the method
 private void gridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {

string appRunPath = Path.GetDirectoryName(System.Windows.Forms.Application.ExecutablePath).ToString();
//above line take the app run path. My image folder was there.


 if (!grdStockDocs.Rows[e.RowIndex].IsNewRow)
            {//this if condition works every row bing to the gridview from datatable (But not new rows.)

if (grdStockDocs.Columns[e.ColumnIndex].Name == "ContentImg")
                {
      if (((string)grdStockDocs.Rows[e.RowIndex].Cells["contentType"].Value) == "text/plain")
                    {
                     e.Value = Image.FromFile(appRunPath + "\\img\\notepad.ico");
                    }
    else if (((string)grdStockDocs.Rows[e.RowIndex].Cells["contentType"].Value) == "image/bmp")
                    {
                        e.Value = Image.FromFile(appRunPath + "\\img\\Image.ico");
                    }
}


}

}

//End of the method.

If any problem please email me.



Comments

Popular Posts