change only the first item in array's back color in listbox

remya1000

Well-known member
Joined
Mar 29, 2007
Messages
122
Programming Experience
Beginner
hi i'm using vb.net.

i have a listbox and its a multiple selected listbox. and i have a array that give the values need to be selected in listbox. So while page load i need to display items to listbox and select the items depends upon the array value. so when the page load depends upon the array it will select multiple items in listbox. and here is the code i used to display mutiple selected items in listbox when listbox is loaded. and array won't be same all the time. depends upon the on textbox value the array keeps on changing.

VB.NET:
Private Sub frmListPromotions_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
               
If File.Exists("C:\Program\data.mdb") Then
            Dim pArray As New ArrayList

            Dim strConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
                               "Data Source=" & "C:\Program\data.mdb" & " "

            Dim myConnection As New OleDbConnection(strConn)
            myConnection.Open()

            Dim schemaTable As DataTable
            'This will get all the table names from Database to DataTable
            schemaTable = myConnection.GetOleDbSchemaTable(OleDb.OleDbSchemaGuid.Tables, New Object() {Nothing, Nothing, Nothing, "TABLE"})

            Dim Table1 As DataTable = New DataTable("Orders")
            Dim Row As DataRow

            Dim Description As DataColumn = New DataColumn("Description")
            Table1.Columns.Add(Description)

            Dim Group As DataColumn = New DataColumn("Group")
            Group.DataType = System.Type.GetType("System.Int32")
            Table1.Columns.Add(Group)

            Dim i As Integer
            For i = 0 To schemaTable.Rows.Count - 1
                Dim NotInArray As Boolean = True

                'Taking Each Table Name from DataTable
                Dim pTableName As String = schemaTable.Rows(i)!TABLE_NAME.ToString

                'Checking the table names Starts with "MG" or "MM"
                If Microsoft.VisualBasic.Left(pTableName, 2) = "MG" Or Microsoft.VisualBasic.Left(pTableName, 2) = "MM" Then
                    Dim strSQL As String = "Select Description, Group, pl1 from " & pTableName & " where [Group] <> 0"
                    Dim myCommand As OleDbCommand = New OleDbCommand(strSQL, myConnection)
                    Dim myReader As OleDbDataReader = myCommand.ExecuteReader
                    While myReader.Read
                        'If NotInArray =True, then write to DataTable
                        NotInArray = True
                        Dim j As Integer
                        If pArray.Count > 0 Then
                            For j = 0 To pArray.Count - 1
                                'Checking whether Description already exist in Array(already added to DataTable)
                                'No duplication of Description in DataTable File
                                If pArray(j).ToString = myReader(0) Then
                                    'If Description is already Added in DataTable file then don't write to DataTable
                                    NotInArray = False
                                    Exit For
                                End If
                            Next
                        End If

                        'Write to DataTable, this Description is not Added before
                        If NotInArray = True Then
                            pArray.Add(myReader(0))
                            Row = Table1.NewRow()
                            Row("Description") = Trim(myReader(0)) & "   [" & myReader(1) & "]" & "  [" & myReader(2) & "]"
                            Table1.Rows.Add(Row)
                        End If
                    End While
                    myReader.Close()
                End If
            Next
            myConnection.Close()

            Dim objDataView As New DataView(Table1)
            objDataView.Sort = "Description ASC"
            ListBox1.DataSource = objDataView
            ListBox1.DisplayMember = "Description"
            ListBox1.ValueMember = "Group"
            ListBox1.SelectedValue = ""

            SelectMultipleValuesListBox(Table1)

        Else
            MessageBox.Show("No file exist")
        End If
    End Sub

Function SelectMultipleValuesListBox(ByVal sTable As DataTable)

        Dim objDataView As New DataView(sTable)
        objDataView.Sort = "Description ASC"

        Dim dvRow As DataRowView
        Dim i As Integer = 0
        Dim g As Integer = 0

CheckNextValue:
        i = 0
        For Each dvRow In objDataView
            i = i + 1
            If aryListBox.Count - 1 < g Then
                Exit For
            End If
            If dvRow.Item(0).split("[")(1).split("]")(0) = aryListBox(g).ToString Then
                ListBox1.SelectedIndex = i - 1
                g = g + 1
                GoTo CheckNextValue
            End If
        Next

    End Function

now according to the array i can select multiple items in listbox. for that i used the code
VB.NET:
ListBox1.SelectedIndex = i - 1

is there anyway i can change only the first item in array's back color in listbox.
Eg: array {100,200,300}. so in my listbox item 100,200,300 will be selected when page load. i need to change only the back color of item 100 or fore color of item 100.

and i try this code...
VB.NET:
ListBox1.SelectedIndex = i - 1
ListBox1.Items(i - 1).BackColor = System.Drawing.Color.Red
ListBox1.Items(i - 1).ForeColor = System.Drawing.Color.White

but error occurs for this code...
An unhandled exception of type 'System.MissingMemberException' occurred in microsoft.visualbasic.dll

Additional information: Public member 'ForeColor' on type 'DataRowView' not found.

if you have any idea, please let me know. i'm not getting any help while searching. so if you have any idea please help me and if you can provide an example then it will be great help for me.

thanks in advance.
 
Set DrawMode for Listbox to 'OwnerDrawFixed' and handle DrawItem event. There is code sample and more explanations in documentation.
 
Thank a lot for your help....

in my list box data will be in this formate.
Remya [100] [1]
George [500] [3]
Peter [300] [4]
Mathew [100] [7]
John [200] [2]
Alex [400] [1]
Philip [200] [5]

for example my array is {100,200,300}. then i need to select Remya [100] [1], John [200] [2], Peter [300] [4]. in list box these numbers repeats, so i will selected only the first item in list having array values. Eg: first item in array is {100}. and i have two items with number 100 (Remya [100] [1], Mathew [100] [7]). but i will select Remya [100] [1]. because its the first item in list have value 100. and i have items inside a Datatable. and have a DataView were i sort the data and the added to Listbox. so how can i give only the selected item to change color.

i found a code from net...
VB.NET:
Private Sub DrawItemHandler(ByVal sender As Object, ByVal e As DrawItemEventArgs) Handles ListBox1.DrawItem

        e.DrawBackground()
        e.DrawFocusRectangle()

        Dim textFont As Font
        textFont = New Font(e.Font.FontFamily, e.Font.Size * 1)

       e.Graphics.DrawString(ListBox1.Items(e.Index).ToString(), textFont, New SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y)

    End Sub 'DrawItemHandler

    Private Sub MeasureItemHandler(ByVal sender As Object, ByVal e As MeasureItemEventArgs)
        e.ItemHeight = 22
    End Sub 'MeasureItemHandler

but now inside listbox instead of items its coming like
System.Data.DataRowView

if you have any idea please help me. i'm not getting any idea... please help me... and if you can provide an example then it will be great help for me.

thanks in advance.
 
As you can read the bound ListBox1.Items are DataRowViews, which is a "view" of the datarow the item is bound to. To get the item text there exist a convenient Listbox function called GetItemText that you should use. The reason I mentioned DataRowView is that you do have the option to dig into that also, by casting the listbox item to this type you can access all columns of the datarow the item is representing, it could be useful in some cases of conditional formatting. But stick to GetItemText to get the text to draw, because that is what your bound control was set up to display in the first place.
 
hi thanks for your reply...

Right now i have all data's inside a DataTable and i'm binding that DataTable to Listbox.

without binding DataTable to a ListBox, is there anyother way i can write each item to listbox from DataTable using OwnerDrawFixed.

For OwnerDrawFixed i got this example.

VB.NET:
Private Sub DrawItemHandler(ByVal sender As Object, ByVal e As DrawItemEventArgs) Handles ListBox1.DrawItem

        e.DrawBackground()
        e.DrawFocusRectangle()

        Dim textFont As Font
        textFont = New Font(e.Font.FontFamily, e.Font.Size * 1)

       e.Graphics.DrawString(ListBox1.Items(e.Index).ToString(), textFont, New SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y)

    End Sub 'DrawItemHandler

    Private Sub MeasureItemHandler(ByVal sender As Object, ByVal e As MeasureItemEventArgs)
        e.ItemHeight = 22
    End Sub 'MeasureItemHandler

in the code below its taking Listbox1.items(e.index).tostring() that used to draw each item to listbox. but how do we send each items in DataTable to draw. How it takes each items in DataTable. once we finish creating DataTable i need to sort this table. so i use DataView for sorting. how can i send the sorted items to draw.

VB.NET:
e.Graphics.DrawString(ListBox1.Items(e.Index).ToString(), textFont, New SolidBrush(e.ForeColor), e.Bounds.X, e.Bounds.Y)

but i couldn't find a way to draw DataTable values through OwnerDrawFixed.

And i'm new to programing so don't have much experience, so can you please help. Anyway i can draw each items in DataTable to Listbox.

if you have any idea please let me know and if you can provide any example then it will be great help for me.

thanks in advance.
 
hello!?!
ListBox1.GetItemText(ListBox1.Items(e.Index))
 
heah... thank's a lot... it works perfectly... and now i can change Fore color of items in Listbox according to my conditions...

Really thanks a lot for this help... and thanks for the time you spend for this... Once again thanks for that... it help me lots.... Thanks...
 
Back
Top