Reputation: 2649
I have a Datagridview
populated by data from my database.
I have 3 columns on my database table: id, name, status.
However these are all in text/string format.
Based on the data I get from the status column of my database(Online or Offline), I try to place an image on the cell, instead of just a plain Online or Offline string.
I attached my DGV
to the DataBindingComplete
event. Currently have this code:
void DataGridView1DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
foreach (DataGridViewRow r in dataGridView1.Rows)
{
if (r.Cells["status"].Value.ToString() == "Online")
{
// add online image here
r.Cells["status"].Value = Resource1.MyOnlineIcon;
}
else if(r.Cells["status"].Value.ToString() == "Offline")
{
// add offline image here
r.Cells["status"].Value = Resource1.MyOfflineIcon;
}
}
But the problem is that it shows System.Drawing.Bitmap
on the cell, instead of actually displaying the picture. Since in my database, the data type for the status column is string, the DGV also makes the column of string type. How do I change the existing string/text type column to an image column? What would be the best way to solve this issue?
Upvotes: 1
Views: 3004
Reputation: 73452
You need to use DataGridViewImageColumn to display the image in DataGridViewCell.
Am not sure whether you can set the column type for existing columns(I believe not possible). Anyhow, you can manually create columns by setting DataGridView.AutoGenerateColumns
to false.
dataGridView1.AutoGenerateColumns = false;
dataGridView1.Columns.Add(new DataGridViewImageColumn
{
DataPropertyName = "YourImageColumnName",
Name = "status"
});
dataGridView1.DataSource = yourDataSource;
Upvotes: 1
Reputation: 3611
If you convert your database query to a Collection of objects like this
public class SomeObject {
public int ID {get;set;}
public string Name {get;set;}
public Bitmap Image {get;set;
public SomeObject(int id, string name, string status) {
ID = id;
Name = name;
Image = status == "Online" ? Resource1.MyOnlineIcon : Resource1.MyOfflineIcon;
}
}
It should work just fine by binding it to the DataGridView
:
List<SomeObject> source = dbConnection.GetObjects();
dataGridView.DataSource = source;
Upvotes: 1