In this section, we will add the image into the DataGrid View of WinForm on the basis of certain conditions.
Here, we have used ImageList control for holding the images and DataGrid View control for displaying the image in the cell with the help of cellPainting() event of data grid view.
Steps to add an image in DataGrid View control dynamically.
Step 1
Drag and drop the DataGrid View and the image list control over WinForm.
Step 2
Add the images to ImageList control.
Step 3
Create a sample data table for binding with the DataGrid View.
- publicDataTable GetTable() {
-
- DataTable table = newDataTable();
- table.Columns.Add("Id", typeof(int));
- table.Columns.Add("Name", typeof(string));
- table.Columns.Add("ImageName", typeof(string));
-
- table.Rows.Add(2, "Pankaj", "PankajImg");
- table.Rows.Add(3, "Manoj", "ManojImg");
- table.Rows.Add(4, "DigVijay", "DigVijayImg");
- table.Rows.Add(5, "Sumit", "SumitImg");
- table.Rows.Add(6, "Varun", "VarunImg");
- return table;
- }
Step 4
Bind the DataGrid View with data table on the form load event.
- privatevoid frmAddImageDynamicallyOnDataGridViewCell_Load(object sender, EventArgs e) {
-
- dataGridOfImage.DataSource = GetTable();
- }
Step 5
Use cellPainting() event of DataGrid View for adding the image over cell.
-
-
-
-
-
- privatevoid dataGridOfImage_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
- if (e.RowIndex > -1 && e.ColumnIndex > -1) {
-
- Image imgForGridCell = null;
-
- if (dataGridOfImage.Columns[e.ColumnIndex].Name.Contains("ImageName")) {
-
-
- if (e.Value.ToString().Equals("AjayImg")) {
-
- imgForGridCell = imageListOfMembers.Images["Ajay"];
- }
- elseif(e.Value.ToString().Equals("PankajImg")) {
- imgForGridCell = imageListOfMembers.Images["Pankaj"];
- }
- elseif(e.Value.ToString().Equals("ManojImg")) {
- imgForGridCell = imageListOfMembers.Images["Manoj"];
- }
- elseif(e.Value.ToString().Equals("DigVijayImg")) {
- imgForGridCell = imageListOfMembers.Images["DigVijay"];
- }
- elseif(e.Value.ToString().Equals("SumitImg")) {
- imgForGridCell = imageListOfMembers.Images["Sumit"];
- }
- elseif(e.Value.ToString().Equals("VarunImg")) {
- imgForGridCell = imageListOfMembers.Images["Varun"];
- }
- if (imgForGridCell != null) {
- SolidBrush gridBrush = newSolidBrush(dataGridOfImage.GridColor);
- Pen gridLinePen = newPen(gridBrush);
- SolidBrush backColorBrush = newSolidBrush(e.CellStyle.BackColor);
- e.Graphics.FillRectangle(backColorBrush, e.CellBounds);
-
- e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left, e.CellBounds.Bottom - 1, e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
- e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1, e.CellBounds.Top, e.CellBounds.Right - 1, e.CellBounds.Bottom);
-
- e.Graphics.DrawImage(imgForGridCell, e.CellBounds.Location);
- dataGridOfImage.Rows[e.RowIndex].Cells["ImageName"].ReadOnly = true;
- }
- e.Handled = true;
- }
- }
- }