Highlight or bold part of the test in Listview items and SubItems

Posted on 2006-04-19
Last Modified: 2012-05-05

I'm displaying a serch results in a listview(windows application) and I need to highlight the searched text within the results. Can anyone pls help?

Question by:dayandealwis
    LVL 96

    Expert Comment

    by:Bob Learned
    You can change the BackColor/ForeColor for a ListViewItem and ListViewItem.ListViewSubItem.

    Dim item As ListViewItem = Me.ListView1.Items.Add("Test")
    item.BackColor = Color.Red
    item.ForeColor = Color.White

    Dim subItem As ListViewItem.ListViewSubItem
    subItem = item.SubItems.Add("Test 2")
    subItem.BackColor = Color.Red
    subItem.ForeColor = Color.White



    Author Comment

    But I want to change only part of the text, not the whole text of the Item or SubItem.
    I believe this has to be done by extending the Listview control and using the ownerdraw method. Can anyone help pls.

    LVL 96

    Expert Comment

    by:Bob Learned
    So, the search text is a sub-part of a ListViewItem.  You gotta start with the easy thing first, and then after finding out the "real" requirement, go from there ;)

    Extending the ListView is not a trivial pursuit.  Are you married to the idea of using the ListView, or can you use a ListBox?


    Author Comment

    Yes, it has to be a ListView. It's been intregated to the system and now only this part has to be completed. I sure do appreciate your help. :)

    LVL 96

    Accepted Solution


    This is what I have so far (incomplete):

    Imports System.Runtime.InteropServices
    Imports System.Drawing

    Public Class ListViewEx
      Inherits System.Windows.Forms.ListView

      <DllImport("User32.dll", CharSet:=CharSet.Auto)> _
      Public Shared Function GetWindowLong(ByVal hwnd As IntPtr, ByVal nIndex As Integer) As Long
      End Function

      <DllImport("User32.dll", CharSet:=CharSet.Auto)> _
      Public Shared Function SetWindowLong(ByVal hwnd As IntPtr, ByVal nIndex As Integer, ByVal dwNewLong As Long) As Long
      End Function

      Public Delegate Sub DrawItemEventHandler(ByVal sender As Object, ByVal e As DrawItemEventArgs)
      Public Event DrawItem As DrawItemEventHandler

      Protected Overridable Sub OnDrawItem(ByVal e As DrawItemEventArgs)

        Dim item As ListViewItem = Me.Items(e.Index)
        Dim text As String = item.Text

        If text.Length > 0 Then
          Dim textBrush As New SolidBrush(item.ForeColor)
          Dim fillBrush As New SolidBrush(item.BackColor)
          Dim rect As RectangleF = RectangleF.op_Implicit(e.Bounds)
          e.Graphics.FillRectangle(fillBrush, rect)
          e.Graphics.DrawString(text, e.Font, textBrush, rect)
        End If

      End Sub

      Protected Overrides Sub OnHandleCreated(ByVal e As System.EventArgs)
        Dim style As Long = GetWindowLong(Me.Handle, -16)
        style = style Or (&H400 Or &H1)
        SetWindowLong(Me.Handle, -16, style)
      End Sub

      <StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
      Public Structure DRAWITEMSTRUCT
        Public ctrlType As Integer
        Public ctrlID As Integer
        Public itemID As Integer
        Public itemAction As Integer
        Public itemState As Integer
        Public hwnd As IntPtr
        Public hdc As IntPtr
        Public rcItem As Rectangle
        Public itemData As IntPtr
      End Structure

      Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message)

        Const WM_DRAWITEM As Int32 = &H2B
        Const WM_REFLECT As Int32 = &H2000
        Const ODS_SELECTED As Int32 = &H1

        Select Case m.Msg

            ' Reflected WM_DRAWITEM
            ' Get the DRAWITEMSTRUCT from the LParam of the message
            Dim dis As DRAWITEMSTRUCT = CType(Marshal.PtrToStructure(m.LParam, GetType(DRAWITEMSTRUCT)), DRAWITEMSTRUCT)

            ' Get the graphics from the hdc field of the DRAWITEMSTRUCT
            Dim g As Graphics = Graphics.FromHdc(dis.hdc)

            ' Create new DrawItemState in its default state          
            Dim state As DrawItemState = DrawItemState.Default

            ' Set the correct state for drawing
            If dis.itemState And ODS_SELECTED > 0 Then
              state = DrawItemState.Selected
            End If

            ' Create the DrawItemEventArgs object
            Dim e As New DrawItemEventArgs(g, Me.Font, dis.rcItem, dis.itemID, state)


          Case Else

        End Select

      End Sub

    End Class

    I doesn't handle bolding part of the ListViewItem.  I'll have to give that some more thought.


    Author Comment

    Thanks for looking into this Bob. Hope U can come up with the solution soon. Thanks again



    Author Comment


    One more thing, above code only handles adding of Items. I need to add subItems also. Can U pls tell me how to extend this to add subItems also.




    Featured Post

    Top 6 Sources for Identifying Threat Actor TTPs

    Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

    Join & Write a Comment

    Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
    Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
    Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
    Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

    728 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    20 Experts available now in Live!

    Get 1:1 Help Now