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

感情迁移 提交于 2019-12-25 03:17:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!