在 drawmode 设置为 ownerdrawfixed 的列表框中选择项目

Selecting items in a listbox with drawmode set to ownerdrawfixed

我有一个列表框,我希望其中的一些项目具有不同的颜色,我明白要做到这一点,我必须将绘图模式设置为 ownerdrawfixed。这工作正常,但是,现在我无法检索选定的项目。当 drawmode 设置为正常时,当我单击列表框中的一个项目时,我让它将该文本放入文本框中。当 drawmode 设置为 ownerdrawfixed 时,当我点击一个项目时,我得到一个错误,“从类型 'item' 到类型 'string' 的转换无效。此外,列表框不再排序,即使已排序的 属性 设置为 true(在 ownerdrawfixed 模式下)。

Public Class Form1

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim ac As Integer
        LstAll.DrawMode = DrawMode.OwnerDrawFixed
        MaxRec = 708
        ChkShow = True

        FileOpen(1, "C:\MyMov3\MovData.mdt", OpenMode.Random, , , Len(Mv3Rec))
        For x = 1 To MaxRec
            FileGet(1, Mv3Rec, x + 1)

            'This If loop for the colored text
            If Mv3Rec.Rc3Mlti = True And ChkShwMlti.Checked = True Then
                ac = Asc(Trim(Mv3Rec.Rc3MTitle))
                If ac > 0 Then
                    Dim i As New Item()
                    i.ItmColor = Color.Red
                    i.Txt = Trim(Mv3Rec.Rc3MTitle)
                    LstAll.Items.Add(i)
                End If
            End If

            If ChkShow = True Then
                Dim i As New Item()             'Needed for the black text when in ownerdrawfixed mode
                i.ItmColor = Color.Black        'Needed for the black text when in ownerdrawfixed mode
                i.Txt = Trim(Mv3Rec.Rc3Title)   'Needed for the black text when in ownerdrawfixed mode
                LstAll.Items.Add(i)             'Needed for the black text when in ownerdrawfixed mode
                'LstAll.Items.Add(Trim(Mv3Rec.Rc3Title))        'This line adds the text when in normal mode
            End If
        Next
        FileClose(1)
    End Sub

    Private Sub LstAll_DrawItem(sender As Object, e As System.Windows.Forms.DrawItemEventArgs) Handles LstAll.DrawItem
        If e.Index < 0 Then Return

        Dim i As Item
        i = TryCast(LstAll.Items(e.Index), Item)

        If i IsNot Nothing Then
            e.Graphics.DrawString(i.Txt, e.Font, New SolidBrush(i.ItmColor), e.Bounds)
        End If
    End Sub

    Private Sub LstAll_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles LstAll.SelectedIndexChanged
        TextBox1.Text = LstAll.SelectedItem
    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        End
    End Sub
End Class

Public Class Item
    Public Txt As String
    Public ItmColor As Color
End Class

此代码只是基本部分....并在新项目中的空白表单上进行了测试。带有一个Listbox(改名为LstAll) 一个textbox,一个checkbox(改名为ChkShwMlti)。这给出了与我需要它在其中工作的程序中相同的错误。但是它确实使用了一个我没有包含结构的文件......但我想你可以明白这个想法。

我已经解决了这个问题。在LstAll.SelectedIndexChanged

Private Sub LstAll_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) handles LstAll.SelectedIndexChanged

    Dim i As New Item
    i = LstAll.SelectedItem
    TextBox1.Text = i.Txt

结束子

这按需工作。