0
votes

I have a DGV named dataGridView1 that has two columns, an image column and a string column. I also have a custom Collection of data that I use to populate the DGV. In my particular application, each row will have a specified string in the string column and one of two images in the image column. I am having trouble with displaying the correct image in the image column when the DGV populates.

This is how I am filtering the data to what I want to put in the DGV:

var match = Core.Set.Servers.Where(ServerItem => ServerItem.GameTag == text);

Currently, I am doing this to populate the DGV:

dataGridView1.AutoGenerateColumns = false;
source = new BindingSource(match,null);
dataGridView1.DataSource = source;

However, the image cells just show the default broken image icon. My icon is located in

Directory.GetCurrentDirectory() + "//Images/favorite.png";

Is there a good way using a DataTable or even a BindingSource? Each item in the collection has two useful features: ServerItem.ServerName and ServerItem.IsFavorite. The first is a string, the second is a boolean. I want the favorite icon to be displayed in the icon column of each row that has IsFavorite==true.

1
I can't quite understand the question and how it corresponds to the question header. Do you have a problem with displaying an image in bound dgv or in editing some cell? Could you please reformat it?d_z
@d_z The question title is fine, but I reworded it slightly. How can I set a column in a row to a particular image based off of a piece of data in the dataset?Jerry

1 Answers

0
votes

To show an image in a bound DataGridView based on a data value you should handle CellFormatting event of the DataGridView. I would recommend store an image in some memory structure like ImageList to avoid roundtrips to storage. Here is a snippet:

List<Row> data = new List<Row>
{
    new Row { IsFavorite = true },
    new Row { IsFavorite = false },
};

dataGridView1.Columns.Add(new DataGridViewImageColumn(false));
dataGridView1.Columns[0].DataPropertyName = "IsFavorite";
dataGridView1.Columns[0].DefaultCellStyle.NullValue = null;
dataGridView1.DataSource = data;

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        if (e.Value != null && e.Value is bool)
        {
            if ((bool)e.Value == true)
            {
                e.Value = imageList1.Images[0];
            }
            else
            {
                e.Value = null;
            }
        }
    }
}

public class Row
{
    public bool IsFavorite { get; set; }
}

And there is another advice: to combine a path from parts you can use Path.Combine(string[])

Hope this helps.