Results 1 to 22 of 22

Thread: [RESOLVED] clickable list of custom colours linked to text file. Suggestions please

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Sep 2010
    Location
    Glogow, Poland
    Posts
    104

    Resolved [RESOLVED] clickable list of custom colours linked to text file. Suggestions please

    Hi,

    Please help me with this one as I'm completely puzzled.

    I would like to create a little list in my Windows Form showing a list of custom colors with their 'friendly names'. Technically it can be anything (ListBox, ListView, Panel etc... whatever).

    I simply want it to look something like this:


    I would like to store data for this list in a simple TXT file in such form:

    Blue,Blue
    Red,Red
    #F6A118,My favourite color
    #004080,Another color

    And of course I would like each element on such list to be clickable, so if I'd click 'My favourite color' it should return the color's HEX value (#F6A118).

    Any suggestions? Where do I start? What do I need to achieve it?

    thanks in advance.

  2. #2
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: clickable list of custom colours linked to text file. Suggestions please

    The easiest is probably a ListView with two columns, one that shows the color (as the BackColor of the ListViewItem) and another that shows the name.

    Then you need two methods:
    - one to load the colors, which means reading the text file line by line, and for each line creating a new ListViewItem. You'll need to split each line along the comma to separate the color and name.
    - another to save the items back to the text file. You'd need to loop through the ListView.Items collection and, for each item, write a new line to the text file.

    If you want to retrieve the color when a listview item is selected, there are multiple ways to do it. The most common is probably to store the color object in the Tag property of each listview item. However, in this case that is a little redundant because you already have your color: the BackColor property of the item.


    I think I've mentioned everything you need, so you should have a lot to google.

  3. #3

    Thread Starter
    Lively Member
    Join Date
    Sep 2010
    Location
    Glogow, Poland
    Posts
    104

    Re: clickable list of custom colours linked to text file. Suggestions please

    thanks for the reply NickThissen.

    I don't really need to save items back from listview to text file. Saving to text file will be done using completely different process, so nothing to do here.

    I'll give it a go and try to google out something about your proposal.

    @ anybody else : Any other suggestions? Maybe some little code examples based on NickThissen's proposal? Please

  4. #4
    VB For Fun Edgemeal's Avatar
    Join Date
    Sep 2006
    Location
    WindowFromPoint
    Posts
    4,255

    Re: clickable list of custom colours linked to text file. Suggestions please

    Quote Originally Posted by marl View Post
    @ anybody else : Any other suggestions? Maybe some little code examples based on NickThissen's proposal? Please
    Not sure this would help or not, its a DropDownCombo with colors and names, can download the project near bottom of page,
    http://www.devx.com/dotnet/Article/8014/1763/page/3

  5. #5
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: clickable list of custom colours linked to text file. Suggestions please

    You might want to consider XML rather than a simple text file. What you have shown is simple enough that it should work fine, but if you get any more complicated, then XML would make more sense. The point behind XML is saving rather more comlicated data to a stylized text file (you can still open it with any text editor, but you can also see the tags) in such a way that you can get specific items back out of it.

    There are lots of built in tools for working with XML files, too, so you would be able to suck the data in somewhat more easily. Sill, it is probably overkill if the example you showed is really all your files will be.
    My usual boring signature: Nothing

  6. #6

    Thread Starter
    Lively Member
    Join Date
    Sep 2010
    Location
    Glogow, Poland
    Posts
    104

    Re: clickable list of custom colours linked to text file. Suggestions please

    @ Edgemeal - thanks, but it does not work in VS2010 properly (or maybe only on my computer). Also the solution itself is so complicated that I simply do not understand it.

    @ Shaggy Hiker - I'm using XMLs in another part of my little project, but in this case it does not really matter how I store the data. I simply have no idea how to display such list based on data from external file.

    I'm still stuck. Been googling for stuff proposed by NickThissen, but no luck so far

  7. #7
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: clickable list of custom colours linked to text file. Suggestions please

    I would do something slightly different from what Nick suggested, but it would probably make your problem worse, rather than better. I find that the ListView is a very powerful control for displaying data like that, but it is also relatively little used, and not so well documented, so every time I actually use one, I have to spend an inordinate amount of time figuring it out.

    For one thing, the ListView comes in all kinds of modes. After all, that's what displays the files in a folder. That's one listview, whether you look at large icons, small icons, detail view (which is multiple columns of data, and totally unlike either of the previous modes), and others. One of the modes (the property is called View, but Mode seems more appropriate) is List. I am currently using a ListView in List mode to show an icon followed by a string. You could take your color from the file, create a small (32x32) bitmap of that color, and show that as the icon beside the name in a Listview in List mode. On the other hand, I wouldn't necessarily say that it was easy, because you have to root around in the details of ListView.

    Here's the code I am using to fill a ListView called lvSideIcons:
    Code:
    lvSideIcons.SmallImageList.Images.Add(I.DisplayFactors.DisplayIcon32x32)
    nI = New ListViewItem(I.ModuleName, lvSideIcons.SmallImageList.Images.Count - 1)
    nI.ToolTipText = I.ModuleToolTip
    lvSideIcons.Items.Add(nI)
    In this case, the first line is where I put the 32x32 bitmap. In the next line, I create a new ListViewItem giving it the string to display (that's where I have I.ModuleName, and you would have the color name), followed by the image. Whether or not there is an easier way, I couldn't say. I then add a tooltip for the item, which you can skip, and finally add the ListViewItem to the Items collection of the ListView itself.
    My usual boring signature: Nothing

  8. #8
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: clickable list of custom colours linked to text file. Suggestions please

    I forgot to mention to put the ListView in Details mode (good point Shaggy) as this is the only view capable of showing sub-items. An image for the color could work (and then you don't need sub-items indeed) but I think simply using the parent item's BackColor is easier.

    What I was proposing is actually extremely easy, I was just trying to let you figure it out on your own:
    vb Code:
    1. Private Sub LoadColors()
    2.    'Load txt file:
    3.    Dim lines As String() = System.IO.Files.ReadAllLines("C:/file.txt")
    4.  
    5.    'Clear existing first
    6.    ListView1.Items.Clear()
    7.  
    8.    For Each line As String In lines
    9.  
    10.       'Split the line along the comma
    11.       Dim parts As String() = line.Split(","c)
    12.  
    13.       'Parse the color
    14.       Dim color As Color = Color.FromKnownName(parts(0))
    15.  
    16.       'Create the listview item
    17.       Dim lvi As New ListViewItem()
    18.       lvi.BackColor = color
    19.       lvi.SubItems.Add(parts(1)) 'add the name
    20.      
    21.       ListView1.Items.Add(lvi)
    22.  
    23.    Next
    24. End Sub

    For parsing the color I am just using FromKnownName (I'm sure there is a function like that but I don't know if that's the correct name, it should parse "Red", "Blue", etc), but you seem to want different ways of storing the color including hex. What you could do is just try a couple different methods in turn; if one fails you try the next.

    Either that or force a single way of specifying the color. The easiest is to use ToArgb() on a Color object (which returns an integer number) and then Color.FromArgb(int) to load it back.

  9. #9

    Thread Starter
    Lively Member
    Join Date
    Sep 2010
    Location
    Glogow, Poland
    Posts
    104

    Re: clickable list of custom colours linked to text file. Suggestions please

    Thanks Shaggy Hiker & NickThissen.

    Thanks to both of you I'm almost there

    My ListView's type of view is set to 'List' ( ListView1.View = View.List ).

    I only slightly modified the code proposed by NickThissen and I can display the colours correctly, but I have no idea how to display the text next to each colour.

    This is my code:
    Code:
    Imports System.IO
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
    ListView1.View = View.List
    
            'Load txt file:
            Dim lines As String() = IO.File.ReadAllLines("C:\colour_test.txt")
    
            'Clear existing first
            ListView1.Items.Clear()
    
            For Each line As String In lines
                'Split the line along the comma
                Dim parts As String() = line.Split(","c)
    
                'Parse the color
                Dim color As Color = System.Drawing.ColorTranslator.FromHtml(parts(0))
                'Dim color As Color = color.FromKnownColor(parts(0))
    
    
                'Create the listview item
                Dim lvi As New ListViewItem()
                lvi.BackColor = color
                lvi.SubItems.Add(parts(1)) 'add the name
                ListView1.BeginUpdate()
                ListView1.Items.Add(lvi)
                ListView1.EndUpdate()
                ListView1.Refresh()
            Next
        End Sub
    
    End Class
    The TXT file is the same as in my initial example.

    This is what I get:


    I tried to display the text, but I failed. I know they are being read as I can show them in Msgbox ( MsgBox(parts(1).ToString) ).

    How to I get those text to be displayed next to the colours?

    Any ideas what is wrong in the above code?

    The other question is how to make each item on the list (Color or text next to it) clickable, but lets leave it for a time being as I may sort it myself.
    Last edited by marl; Aug 22nd, 2011 at 10:37 AM. Reason: typo corrected

  10. #10
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: clickable list of custom colours linked to text file. Suggestions please

    Quote Originally Posted by marl View Post
    My ListView's type of view is set to 'List' ( ListView1.View = View.List ).
    That's your problem. As I explained, only the Details view is capable of showing sub-items, the others don't show them. You'll also need to add two columns via the Columns property. The main item will be shown in the first column and the first sub-item is shown in the second column.

    This should also solve your selection problem; the items were already selectable but you couldn't see that because your entire item is just one block of colors.
    You might want to set the FullRowSelect property to True though, then it also shows the selection rectangle in the sub-items.

  11. #11

    Thread Starter
    Lively Member
    Join Date
    Sep 2010
    Location
    Glogow, Poland
    Posts
    104

    Re: clickable list of custom colours linked to text file. Suggestions please

    Ok - understood NickThissen.

    This is my new code:

    Code:
    Imports System.IO
    Public Class Form1
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            ListView1.View = View.Details
            ListView1.Columns.Add("Color", 50, HorizontalAlignment.Left)
            ListView1.Columns.Add("Name", 120, HorizontalAlignment.Left)
    
            'Load txt file:
            Dim lines As String() = IO.File.ReadAllLines("C:\colour_test.txt")
    
            'Clear existing first
            ListView1.Items.Clear()
    
            For Each line As String In lines
                'Split the line along the comma
                Dim parts As String() = line.Split(","c)
    
                'Parse the color
                Dim color As Color = System.Drawing.ColorTranslator.FromHtml(parts(0))
                'Dim color As Color = color.FromKnownColor(parts(0))
    
    
                'Create the listview item
                Dim lvi As New ListViewItem()
                lvi.BackColor = color
                lvi.SubItems.Add(parts(1)) 'add the name
                ListView1.BeginUpdate()
                ListView1.Items.Add(lvi)
                ListView1.EndUpdate()
                ListView1.Refresh()
            Next
        End Sub
    
    End Class
    This is what I get:


    But how do I make the 'Name' column's background white? Is it possible?

  12. #12
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: clickable list of custom colours linked to text file. Suggestions please

    There is a property on each item that determines whether the sub-items are styled in the same way as the main item. I can never remember the name but it's something like UseItemStyleForSubItems, or similar, you'll find it if you look for 'Use'. Set it to False.

  13. #13
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: clickable list of custom colours linked to text file. Suggestions please

    This is actually a good reason to use the View style. As long as your colors are fixed, you can always set the text color to something that provides good contrast (which might be white in all cases), but that isn't always easy to determine. If there is one color that will provide good contrast for all the colors you have, or will have, then coloring the background will do. If not, then using the View mode will work better, because the text will always be colored. However, it would also mean that you would have to create those solid color bitmaps to show beside the text. The result would look like the drawing you had in your initial post (except that I think the color will be square).
    My usual boring signature: Nothing

  14. #14
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: clickable list of custom colours linked to text file. Suggestions please

    I suppose you mean the List view, instead of the View style?

    I don't see what's wrong with using the Details view and displaying the text in a sub-item. You have all the control you want, you can make the columns as wide as you want (so the colors can be squares or not), etc.
    Most importantly, it's the most natural and easy way to make it work, surely much easier than generating a bitmap for each item?

    Yes, the background carrying over to the sub-items by default is a 'problem', but the UseItemStyleForSubItems property can be set to False and the problem is gone, it doesn't get any easier than that.

  15. #15

    Thread Starter
    Lively Member
    Join Date
    Sep 2010
    Location
    Glogow, Poland
    Posts
    104

    Re: clickable list of custom colours linked to text file. Suggestions please

    thanks Shaggy Hiker. I appreciate your comment, but it looks like in this particular case NickThissen is 100% right.

    This is my new code with amendments proposed by NickThissen (new lines bolded):
    Code:
    Imports System.IO
    Public Class Form1
    Friend WithEvents myListView As System.Windows.Forms.ListView
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            ListView1.View = View.Details
            ListView1.Columns.Add("Color", 50, HorizontalAlignment.Left)
            ListView1.Columns.Add("Name", 120, HorizontalAlignment.Left)
    
            'Load txt file:
            Dim lines As String() = IO.File.ReadAllLines("C:\colour_test.txt")
    
            'Clear existing first
            ListView1.Items.Clear()
    
            For Each line As String In lines
                'Split the line along the comma
                Dim parts As String() = line.Split(","c)
    
                'Parse the color
                Dim color As Color = System.Drawing.ColorTranslator.FromHtml(parts(0))
                'Dim color As Color = color.FromKnownColor(parts(0))
    
    
                'Create the listview item
                Dim lvi As New ListViewItem()
                lvi.UseItemStyleForSubItems = False
                lvi.BackColor = color
                lvi.SubItems.Add(parts(1)) 'add the name
                ListView1.BeginUpdate()
                ListView1.Items.Add(lvi)
                ListView1.EndUpdate()
                ListView1.Refresh()
            Next
        End Sub
    
    End Class
    This is what I get (and this is precisely how I wanted it to look like):



    Now I will try to make those items clickable to return the color Hex value. If you are fancy posting a ready piece of code, please do, as it may take some time before I will figure out how to do it .

    Thanks a lot for all the help so far.

  16. #16
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,102

    Re: clickable list of custom colours linked to text file. Suggestions please

    Ah, that's true. I was thinking that what you were headed towards was a single item colored as you have it, but with the text written over the top, which is where problems with contrast would arise. I also wasn't thinking about an empty subitem. That's a good call.

    As for the Hex value, you have the color, since it is the backcolor or the subitem, is the main issue what event to use? Normally, a ListView is like a ListBox, so you would use the SelectedIndexChanged event, and set the color in that. This may not be what you want to do, though, because that requires that the selected item changes. In other words, if you have Blue selected and click on Blue, no selection change will be raised, so if you really want an action on a click, regardless of what item is selected, then SelectedIndexChanged isn't the right event. It IS the easiest, though, so if it is ok, use it. Alternatively, you would need to handle the Mouse Click event and check the SelectedItem for the color. Not as good, and possibly not as reliable.
    My usual boring signature: Nothing

  17. #17
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    Re: clickable list of custom colours linked to text file. Suggestions please

    This works in the MouseClick event:

    Code:
    Dim item = ListView1.GetItemAt(e.X, e.Y)
    Console.WriteLine(item.BackColor.ToArgb.ToString("X"))
    BB

  18. #18

    Thread Starter
    Lively Member
    Join Date
    Sep 2010
    Location
    Glogow, Poland
    Posts
    104

    Re: clickable list of custom colours linked to text file. Suggestions please

    Thanks for interest boops boops, but what "e.X" and "e.Y" stands for?

    I'm getting and error saying:

    Error 1 'X' is not a member of 'System.EventArgs'.

    Would you be so kind to adapt your code to my above code? I've been trying, but it looks like I'm too thick to do it myself.

    regards

  19. #19
    PowerPoster boops boops's Avatar
    Join Date
    Nov 2008
    Location
    Holland/France
    Posts
    3,201

    Re: clickable list of custom colours linked to text file. Suggestions please

    e is the MouseEventArgs argument of the MouseClick event. e.Y and e.Y give you location of the click relative to the control origin.

    System.Eventargs? That probably means you have chosen the Click event instead of the MouseClick event. BB

  20. #20

    Thread Starter
    Lively Member
    Join Date
    Sep 2010
    Location
    Glogow, Poland
    Posts
    104

    Re: clickable list of custom colours linked to text file. Suggestions please

    Hi All,

    Got it. It works as I wanted.

    Here is the final code:
    Code:
    Imports System.IO
    Public Class Form1
    Friend WithEvents myListView As System.Windows.Forms.ListView
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
            ListView1.View = View.Details
            ListView1.Columns.Add("Color", 50, HorizontalAlignment.Left)
            ListView1.Columns.Add("Name", 120, HorizontalAlignment.Left)
    
            'Load txt file:
            Dim lines As String() = IO.File.ReadAllLines("C:\colour_test.txt")
    
            'Clear existing first
            ListView1.Items.Clear()
    
            For Each line As String In lines
                'Split the line along the comma
                Dim parts As String() = line.Split(","c)
    
                'Parse the color
                Dim color As Color = System.Drawing.ColorTranslator.FromHtml(parts(0))
                'Dim color As Color = color.FromKnownColor(parts(0))
    
    
                'Create the listview item
                Dim lvi As New ListViewItem()
                lvi.UseItemStyleForSubItems = False
                lvi.BackColor = color
                lvi.SubItems.Add(parts(1)) 'add the name
                ListView1.BeginUpdate()
                ListView1.Items.Add(lvi)
                ListView1.EndUpdate()
                ListView1.Refresh()
            Next
        End Sub
    
    Private Sub ListView1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListView1.MouseClick
    
            Dim colorhtml = ListView1.FocusedItem.BackColor
            TextBox1.Text = System.Drawing.ColorTranslator.ToHtml(colorhtml)
    
        End Sub
    
    End Class
    this is the result:



    Thanks a lot NickThissen, Shaggy Hiker and boops boops for answers, tips and interest in my problem in general.

    I will resolve the thread soon if I won't find any major errors in my current code.

    regards

  21. #21
    PowerPoster
    Join Date
    Apr 2007
    Location
    The Netherlands
    Posts
    5,070

    Re: clickable list of custom colours linked to text file. Suggestions please

    I see you're using a 'myListView' field in your code but you're not using that. You probably copied it from some example. You already have ListView1, and myListview is not doing anything, it's not even being placed on your form.

  22. #22

    Thread Starter
    Lively Member
    Join Date
    Sep 2010
    Location
    Glogow, Poland
    Posts
    104

    Re: clickable list of custom colours linked to text file. Suggestions please

    LOL - yes NickThissen - you are correct. This was coppied.

    later I played with the code more so I did not even realised this may not be needed anymore.

    Thanks for pointing out.
    Last edited by marl; Aug 23rd, 2011 at 11:17 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width