选择列表框中的项目,并将drawmode设置为ownerdrawfixed

时间:2017-07-28 19:37:31

标签: vb.net visual-studio-2010 listbox

我有一个列表框,我想要一些项目是不同的颜色,我明白这样做我必须将drawmode设置为ownerdrawfixed。这工作正常,但是,现在我无法检索所选项目。将drawmode设置为normal,当我单击列表框中的某个项目时,我会将该文本放入文本框中。将drawmode设置为ownerdrawfixed,当我单击某个项目时,我收到一条错误“从类型'item'转换为type'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)一个文本框,一个复选框(重命名为ChkShwMlti)。这给出了与我需要它工作的程序相同的错误。但它确实使用了一个我没有包含结构的文件......但我认为你可以理解。

1 个答案:

答案 0 :(得分:0)

我已经发现了这个问题。在LstAll.SelectedIndexChanged

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

nocopy

End Sub

这可以根据需要运作。