Monday, June 15, 2015

VB.NET - Datagridview image and text in one cell

VB.NET - Datagridview image and text in one cell
Clipboard01
How to icon or image in one cell datagridview ?
Step 1 : Create Column "Change"
'Set Column name
Datagridview1.Columns.Add("qsymbol", "Symbol")
Datagridview1.Columns.Add("qdate", "Date")
Datagridview1.Columns.Add("qopen", "Open")
Datagridview1.Columns.Add("qhigh", "High")
Datagridview1.Columns.Add("qlow", "Low")
Datagridview1.Columns.Add("qclose", "Close")
Datagridview1.Columns.Add("qvolume", "Volume")



Step 2 : Store Value to every cell
For Each row As DataRow In pdtdata.Rows
'--- data rows
n = datagridview1.Rows.Add()
datagridview1.Rows(n).Cells("qsymbol").Value = row.Item("qsymbol")
datagridview1.Rows(n).Cells("qname").Value = row.Item("qname")
datagridview1.Rows(n).Cells("qprevclose").Value = row.Item("qprevclose")
datagridview1.Rows(n).Cells("qopen").Value = row.Item("qopen")
datagridview1.Rows(n).Cells("qdhigh").Value = row.Item("qdhigh")
datagridview1.Rows(n).Cells("qdlow").Value = row.Item("qdlow")
datagridview1.Rows(n).Cells("qchange").Value = row.Item("qchange")
Step 3 : Write code below at form
Private Sub DataGridView1_CellPainting(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs) _
Handles DataGridView1.CellPainting
DataGridView_CellPainting(6, sender, e)  '6 is column index of "Change"
End Sub
Step 4 : Write Code below to module
Public Sub DataGridView_CellPainting(ByVal pcolumn As Integer, ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellPaintingEventArgs)
Dim zsignimage As Image = Nothing
Dim format As New StringFormat()
If e.ColumnIndex = pcolumn AndAlso e.RowIndex > -1 Then
Select Case e.Value
Case 0
zsignimage = My.Resources.icon_dot
Case Is > 0
zsignimage = My.Resources.icon_up
Case Is < 0
zsignimage = My.Resources.icon_down
End Select
e.PaintBackground(e.ClipBounds, True) 'transparant in cursor
'draw icon image
format.LineAlignment = StringAlignment.Center
format.Alignment = StringAlignment.Near
Dim x As Integer = (e.CellBounds.Width / 4)
Dim iconRect = New Rectangle(e.CellBounds.Left + 7, e.CellBounds.Top + 1, x - 7, e.CellBounds.Height - 4)
e.Graphics.DrawImage(zsignimage, iconRect)
'draw text
format.LineAlignment = StringAlignment.Center
format.Alignment = StringAlignment.Far
Dim textRect = New Rectangle(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Width, e.CellBounds.Height)
e.Graphics.DrawString(e.Value, zSFont, Brushes.Black, textRect, format)
e.CellStyle.SelectionBackColor = Color.Transparent
e.Handled = True
End If
End Sub
Thank You

2 comments:

  1. Thanks for the nice blog. It was very useful for me. I'm happy I found this blog. Thank you for sharing with us,I too always learn something new from your post. psiprograms.com

    ReplyDelete
  2. Really awesome bro. I need this only. Thank you

    ReplyDelete