问题
I have a Datagridview on my Winform project. The Datagridview is populated by data from my database.
I have 3 columns on my database table: id
, name
, status
.
What I want to do is, based on the status string I get from my database ("Online" or "Offline"), I like to put an image in the cell, instead of just displaying a string of either Online or Offline.
ex.:If the status is Online, I'd like to have my designated online image/icon on the cell.
Anyone have ideas how to approach this?
回答1:
I would do this on the DataBindingComplete event:
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
foreach (DataGridViewRow r in dataGridView1.Rows)
{
if (r.Cells["status"].Value.ToString() == "Online")
{
//add image here
}
}
}
Your datagrid would need to attach to the DataBindingComplete
as well
This answer might also be useful:
https://stackoverflow.com/a/8182203/2589202
回答2:
You can use any of the events of datagridview such as
private void dataGridView1_RowsAdded(object sender,
DataGridViewRowsAddedEventArgs e)
{
// write code to add image path in current cell of the row.
}
void Item_Bound(Object sender, DataGridItemEventArgs e)
{
// write code to add image path in current cell of the row.
}
below links will might you to add image in column
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewimagecolumn.image(v=vs.110).aspx
http://csharp.net-informations.com/datagridview/csharp-datagridview-image.htm
来源:https://stackoverflow.com/questions/25193652/how-to-dynamically-assign-datagridview-cell-values-based-on-data-from-my-databas