简体   繁体   中英

How to dynamically assign Datagridview cell values based on data from my database?

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM