Any way for a combo box with 2 values per line? - vb.net

I'm looking for an option with which I can use the functionality of a combobox together with a
listview.
The reason for this is because I have SQL queries which can't have more than 1 output, which I can get in some cases.
E.g. my SQL table looks somewhat like this
Unique_ID - Name
123456789 - Simon
987654321 - Simon
Basically the same name can be in the database multiple times, each entry with it's own ID.
For the user's sake, I can't have them choose what records to edit based on the ID, instead I have them base the chosen record on the name. When there's more than 1 record resulting from my query though, I get a MySQL exception.
Here's the MySQL query in question:
"SELECT worldspace from survivor where is_dead = '0' _ and survivor.unique_id = (select unique_id from profile where name = '" & target & "')"
The output from that query is then used in another UPDATE query.
So, is it possible for my combobox to have both the ID & the name as values, with a clear seperation between them so the entire value stays well readable, as it would do in a listview element?

I see you've already gotten the HighCore treatment about how easy everything is in WPF and how much WinForms sucks. But you might be interested to know that you can do this in WinForms, too. You just do it a little bit differently. It should come as no surprise that the standard design idioms differ in WinForms and WPF; that doesn't justify one being "better" than the other, it just means you need to learn how to use the one you're using. (Although, admittedly, some of the fancier stuff is a bit more difficult to achieve using a UI framework that was invented 20 years ago with Windows itself. The power it does have is rather remarkable.)
There are two basic ways of formatting the information: everything on a single line (which I believe is what you asked for in the question) or the pieces of information on two lines where each item is basically a two-line unit (which is what HighCore's WPF solution demonstrates).
Single-Line Format
The Simplistic Approach
We'll look at putting everything on a single line first, which really is simple. You don't need columns for separation, you can just use some kind of distinctive separator character when you add the items to the combobox, such as a vertical pipe (|) or a dash (-) like you used in the question.
This works so well because the ComboBox.Items.Add method accepts a parameter of type Object, on which it just calls ToString to get the value displayed in the control. If you pass it a string, it displays that string.
myComboBox.BeginUpdate()
For Each record In myRecordSet
myComboBox.Items.Add(String.Format("{0} | {1}", record.UniqueID, record.Name))
' or even...
myComboBox.Items.Add(String.Format("{0} ({1})", record.UniqueID, record.Name))
Next record
myComboBox.EndUpdate()
OR
An Incremental Improvement Through OOP
You can even pass a custom class to the Add method that keeps track of the unique ID and name properties (and anything else you want) and overrides the ToString method for display purposes.
Public Class Record
Public Property UniqueID As Long ' maybe this should be a string too
Public Property Name As String
Public Overrides Function ToString() As String
' Generate the string that will be displayed in the combobox for this
' record, just like we did above when adding it directly to the combobox,
' except that in this case, it will be dynamically generated on the fly,
' allowing you to also track state information along with each item.
Return String.Format("{0} | {1}", Me.UniqueID, Me.Name)
End Function
End Class
' ...
' (somewhere else, when you add the items to the combobox:)
myComboBox.BeginUpdate()
For Each r In myRecordSet
' Create a Record object representing this item, and set its properties.
Dim newRecord As New Record
newRecord.UniqueID = r.UniqueID
newRecord.Name = r.Name
' ...etc.
' Then, add that object to the combobox.
myComboBox.Items.Add(newRecord)
Next r
myComboBox.EndUpdate()
Fixing the Jaggies
Granted, if the first item in each set can be of variable length and you're using a variable-width font (i.e., one that is not monospaced like every UI on the planet does except code editors), the separators won't line up and you won't get two nicely-formatted columns. Instead, it looks all jumbled and ugly.
It would be nice of the ComboBox control supported tab characters that would handle lining everything up for us automatically, but unfortunately it does not. This is, regrettably, a hard limitation of the underlying Win32 control.
Fixing this ragged-edge problem is possible, but it does get a bit complicated. It requires taking over the drawing of the items in the combobox, referred to as "owner-draw".
To do this, you set its DrawMode property to OwnerDrawFixed and handle the DrawItem event to manually draw the text. You'll use the TextRenderer.DrawText method to draw the caption string (because that matches what WinForms uses internally; avoid using Graphics.DrawString), and TextRenderer.MeasureText if necessary to get the spacing right. The drawing code can (and should) use all of the default properties provided by the DrawItemEventArgs passed as e. You don't need OwnerDrawVariable mode or to handle the MeasureItem event because the width and height of each item cannot vary in this case.
Just to give you an idea, here's a quick-and-dirty implementation that simply divides the drop-down in half vertically:
Private Sub myComboBox_DrawItem(sender As Object, e As DrawItemEventArgs) Handles myComboBox.DrawItem
' Fill the background.
e.DrawBackground()
' Extract the Record object corresponding to the combobox item to be drawn.
Dim record As Record = DirectCast(myComboBox.Items(e.Index), Record)
Dim id As String = record.UniqueID.ToString()
Dim name As String = record.Name
' Calculate important positions based on the area of the drop-down box.
Dim xLeft As Integer = e.Bounds.Location.X
Dim xRight As Integer = xLeft + e.Bounds.Width
Dim xMid As Integer = (xRight - xLeft) / 2
Dim yTop As Integer = e.Bounds.Location.Y
Dim yBottom As Integer = yTop + e.Bounds.Height
' Draw the first (Unique ID) string in the first half.
TextRenderer.DrawText(e.Graphics, id, e.Font, New Point(xLeft, yTop), e.ForeColor)
' Draw the column separator line right down the middle.
e.Graphics.DrawLine(SystemPens.ButtonFace, xMid, yTop, xMid, yBottom)
' Draw the second (Name) string in the second half, adding a bit of padding.
TextRenderer.DrawText(e.Graphics, name, e.Font, New Point(xMid + 5, yTop), e.ForeColor, TextFormatFlags.Left)
' Finally, draw the focus rectangle.
e.DrawFocusRectangle()
End Sub
Now, this is looking pretty good. You can certainly improve on the technique used by the DrawItem event handler method, but it works out pretty well as is, so long as the combobox is made the right size for the values it will be displaying.
Multiple-Line Format
Defining a Custom ComboBox Class
The second method, where each item is a two-line group like HighCore's WPF example, is best done by subclassing the built-in ComboBox control and taking complete control its drawing routines. But that's nothing to be afraid of, subclassing a control is a standard WinForms idiom to gain extra control over the UI. (You could, of course, implement all of this by handling events like I did above, but I think subclassing is a much cleaner approach and also promotes reuse if you want to have multiple comboboxes that all behave in a similar fashion.)
Again, you don't need OwnerDrawVariable because the height of the items is not going to change. You'll always have two lines, so a fixed height works fine. You just need to make sure that you set the ItemHeight property to double of its normal value because you're going to have two lines. You could do this the complicated way using TextRenderer.MeasureText, or you could do it the easy way by just multiplying the default value by 2. I chose the latter for this demo.
Add this class into your project, and then use the MultiLineComboBoxcontrol instead of the built-in System.Windows.Forms.ComboBox. All of the properties and methods work the same.
Public Class MultiLineComboBox : Inherits ComboBox
Public Sub New()
' Call the base class.
MyBase.New()
' Typing a value into this combobox won't make sense, so make it impossible.
Me.DropDownStyle = ComboBoxStyle.DropDownList
' Set the height of each item to be twice its normal value
' (because we have two lines instead of one).
Me.ItemHeight *= 2
End Sub
Protected Overrides Sub OnDrawItem(e As DrawItemEventArgs)
' Call the base class.
MyBase.OnDrawItem(e)
' Fill the background.
e.DrawBackground()
' Extract the Record object corresponding to the combobox item to be drawn.
If (e.Index >= 0) Then
Dim record As Record = DirectCast(Me.Items(e.Index), Record)
' Format the item's caption string.
Dim caption As String = String.Format("ID: {0}{1}Name: {2}", record.UniqueID.ToString(), Environment.NewLine, record.Name)
' And then draw that string, left-aligned and vertically centered.
TextRenderer.DrawText(e.Graphics, caption, e.Font, e.Bounds, e.ForeColor, TextFormatFlags.Left Or TextFormatFlags.VerticalCenter)
End If
' Finally, draw the focus rectangle.
e.DrawFocusRectangle()
End Sub
End Class
Adding Fancies and Flourishes
What we've got now isn't bad, but by lavishing a bit more effort on the drawing code in OnDrawItem, we can add some extra visual fancies and flourishes.
For example, without the selection rectangle, it would be pretty hard to tell that these are actually two-line units. That's unusual for a combobox control, so for usability reasons your application should go out of its way to make this abundantly clear. One way we might do that is by indenting the second line. You'll recall that I said that the built-in combobox control doesn't support tabs? Well that doesn't apply anymore, since we're doing the drawing ourselves now. We can emulate tabs by adding some extra padding to the beginning of the second line.
If you wanted the labels ("ID:" and "Name:") to be set apart from the actual values, you could do that, too. Perhaps you'd make the labels bold and lighten the text color.
So you see that just by playing with the drawing code, you can create almost any effect you want. We have complete control, and by wrapping it all up in a MultiLineComboBox class that can be reused all over the place, the rest of your code doesn't even have to know that anything special is happening. Cool, right?
Avoiding All the Work
And finally, I would be remiss if I didn't point out that you could skip doing all of this work and take your pick of the variety of custom multi-line combobox controls that have already been written.
This one is pretty nifty. It actually just displays a ListView control when you click the drop-down arrow on the combobox. In doing so, you get all of the formatting niceties of the ListView control for free, but it behaves just like a regular ComboBox.

This would be a WPF ComboBox with multiple Lines:
<ComboBox ItemsSource="{Binding}">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding ID, StringFormat='{}ID: {0}'}"/>
<TextBlock Text="{Binding Name, StringFormat='{}Name: {0}'}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
Data Item:
public class ComboItem
{
public int ID { get; set; }
public string Name { get; set; }
}
Result:
To all the hackforms zombies: technical superiority speaks by itself.

The solution is actually way, way easier. Try this:
For i As Integer = 0 To dataSet.Tables(0).Rows.Count - 1
ComboBox1.Items.Add(dataSet.Tables(0).Rows(i)(0) + " | " + dataSet.Tables(0).Rows(i)(1)
+ " | " + dataSet.Tables(0).Rows(i)(2))
Next
But you have to implement it to your Code and DB

Related

VB.Net Selecting LineShape

In Vb.Net, I'm dinamycally creating several textbox and labels. I'm naming them ex. VLabel1, VLabel2, VLabel3 ... and then I use CType and a variable to use them.
Dim VarName as String
Dim i as Integer
Dim MyLabel as Label
i=0
VarName = ("VLabel" & i.ToString)
MyLabel = CType(Panel1.Controls(VarName), Label)
Now I'm adding lines using LineShape (I can't use label having height of 1 because my lines are diagonals). Can I use a similar way to select a specific line or do I have to use a loop in my ShapeContainer and compare names until I find the one I want?
Thank you,
Stephane
do I have to use a loop in my ShapeContainer and compare names until I find the one I want?
What do you think the Controls(VarName) does? It has to lookup the control by name, too. If you're comfortable with that, you can write a method in your form that does the same thing.
But a better option for both the LineShapes and the Labels is use List(Of LineShape) and a List(Of Label). When you create a dynamic control and add or remove it from your form, also add or remove it form your list. Then you can reference these items by index, without needing to build a name string. You'll also have less casting this way.
Another option to index them by name is to use Dictionary(Of String,Lineshape) and Dictionary(Of String, Label). A couple of helper subs can handle adding/removing where needed and adding/removing to the appropriate Dictionary. With this you also eliminate the need for casting as the actual objects are of the correct type already.
Even better yet, since Shapes aren't part of the standard library, I would suggest learning how to draw the lines directly on to your form.
I've never done it, but it should be possible to actually create the lines as controls, by creating a class that inherits from the Control class and overriding the Paint sub to draw the line.

Write individual listbox items into different text boxes and repeat until all text boxes are full

I'm programming in Visual Basic.
I have one form.
Form 1 contains:
nameTextBox
addNameButton
namesListBox
generateButton
week1TextBox
week2TextBox
week3TextBox
week4TextBox
The user needs to go to Form 1 and type a name in the text box, then add the name to the List Box. The user will add 4 names to the List Box. So, the ListBox will contain the names: Adam, Brenda and Carol.
When the generateButton is clicked, the 3 names have to be written to the text boxes in that order. So week1TextBox should contain "Adam", week2TextBox should contain "Brenda", etc... but once the last name (in this case "Carol") is written into the text box, the loop should start over. Ultimately, there may be up to 50 week text boxes (so week50TextBox). So the loop needs to repeat over and over.
As there is a lack of source code in your question, I'm really not sure exactly how the layout should look, I can only offer some advice/suggestions.
I would recommend creating your listbox control, input textbox, and button to add names to the listbox. In addition to these, though, also add a scrollable panel. (Not sure what the exact term for that control is in VB.net; it's been a long time since I've worked with that language.) Because it sounds like there might be a variable number of items on the panel, when the user goes to generate the list of names, I would use the following rough pseudocode:
Dim OutputTexts As New ArrayList ' This is only here if you want to work with these textboxes later
Private Sub CreateOutput() Handles btnGenerate.Click
pOutputPanel.Controls.Clear()
OutputTexts.Clear()
Dim NextX As Integer = 0 ' Pretty much unnecessary value, but included in case you want to mess with this
Dim NextY As Integer = 0
For i As Integer = 0 To Convert.ToInt32(txtWeekCount.Text)
Dim txtName As New TextBox
txtName.Text = lbNameList.Item(i Mod lbNameList.Items.Count)
txtName.Location = new Point(NextX, NextY) ' Play with this as necessary
NextY += 50 ' Play with this as necessary
OutputTexts.Add(txtName)
pOutputPanel.Controls.Add(txtName)
Next
End Sub
Again, this is very much pseudocode, so I would not encourage copying and pasting, but give it a read, make sure you understand all of it, and then try implementing something similar. There might be an easier way to do it, but I have not programmed in VB.NET in probably over 2 years (at least). Nonetheless, the most important thing in here is the following line: lbNameList.Item(i Mod lbNameList.Items.Count). By Mod-ing your indexing variable, you will be accessing items sequentially, and then repeating from the start of the ListBox items collection once i is out of range.
I would also encourage you to dynamically generate your TextBox controls as needed rather than manually adding in 50 or more TextBox controls.

Duplicating control action

In Vb.net I have a button on one form (call it button_abc), changes color, the text changes, has a click event, etc. I want to have the SAME button duplicated on another form so that it can be used from 2 different places (one of the forms might not be visible). When the text or color gets changed on one, it need to appear in both. So if both forms are open, the buttons always appear to match exactly in appearance and action. is there a way to "link" them together automatically?
Copying & pasting a button, simply creates a new (separate) button---not what I want.
I would be inclined to go down the path of using an adapter to allow you to update the buttons.
Something like this:
Public Class ButtonList
Inherits List(Of Button)
Public Property Color() As Color
Get
Return Me.Select(Function (b) b.Color).FirstOrDefault()
End Get
Set(ByVal Value As Color)
For Each b In Me
b.Color = Value
Next
End Set
End Property
' + all other relevant properties.
End Class
Since it inherits from List(Of Button) you just add all the buttons you need to this class using .Add(button) and then put in all of the properties that you want to update. Now the code appears very much the same, but you now will update many buttons at once.
This is along the lines of what I'm describing, except I'm using VB
Duplicate WebControls at Runtime
Since you always want the buttons to match, it doesn't matter if one form is open/visible or not. You simply create 2 buttons, 1 on each form and make them do the same thing on both forms. So some pseudo-code may look like this:
Form 1:
Button.ClickEvent
Me.Color = UglyGreen
Form2.Button.Color = UglyGreen
End Button.ClickEvent
Form 2:
Button.ClickEvent
Me.Color = UglyGreen
Form1.Button.Color = UglyGreen
End Button.ClickEvent
It's not a very pretty solution, but it works for the specified task.

Creating an userform object hierarchy with grouping in vba

First things first. There's a good chance what I want to do should really be done with VB and not VBA. But as long as it is possible I would rather use VBA.
I have a userform of essentially a big diagram made of hundreds of labels. I want to separate these labels into groups. And then separate these groups into subsystems. The idea being I have some form of heirarchy to work with. The label groups need to change color based on what I have selected in a combo box, and if I click on one of these labels I want to bring up a user form showing details of the subsystem using click events.
I'm pretty sure I need to use multiple classes to do what I want but am fairly new to using class modules. Though I get the concept.
Basically I want some functionality that goes subsystem -> label group( or part) -> color with click events for the whole subsystem and combo box events for changing label group colors.
I saw a thread online about grouping labels or text boxes but it only works to trigger the even for a group, not change the properties of the whole group once the event is triggered. I would like to set this up in classes as well so I can export the system for use in other future userforms.
I was able to create groups of labels and change them together like I wanted:
CPart (Class Module 1):
*This is meant to handle the event triggering of the labels and includes some color code that I used to test functionality of the groups changing together and functionality of changing colors.
Public WithEvents trigger As MSForms.Label
Dim pLabels As Collection
Property Set triggers(c As Collection)
Set pLabels = c
End Property
Private Sub trigger_Click()
For Each obj In pLabels
obj.BackColor = RGB(255, 0, 0)
Next obj
End Sub
CTrigger (Class Module 2):
*This took a collection of labels which were passed in through a collection variable in the userform and then stored each label as a trigger in a separate class variable, along with the whole collection of labels in that group. This way when any trigger fires the event, all of the labels change.
Dim CTrigger() As New CPart
Dim pLabels As Collection
Dim i As Integer
Property Set Labels(c As Collection)
Set pLabels = c
For i = 1 To pLabels.Count
ReDim Preserve CTrigger(1 To i)
Set CTrigger(i).trigger = pLabels.Item(i)
Set CTrigger(i).triggers = pLabels
Next i
End Property
Property Get Labels() As Collection
Labels = pLabels
End Property
I really don't like the way it works, partly because I am losing myself in the logic of it constantly, and partly because it means that in order to use this I have to make collections of labels in the userform module anyway just to run it. It is very inefficient code, but I am putting it up so you get an idea of what I am trying to accomplish.
What I would much rather do instead is have one class variable to hold my custom collection of labels (a "LabelGroup"). Another class variable is likely required to hold the labels themselves (I think). And then all I would have to do is go through and write methods for the LabelGroup class such as changecolor, and it could handle that. But I can handle that part, for now what I really need help with is setting up the class framework in a neat way, so that the module I will eventually run could just say things like:
LabelGroup1.Add Label1
LabelGroup2.Add Label2
or
Private Sub button_click()
LabelGroup1.ChangeColor(RGB(...))
End Sub
These two articles have been helping me along:
http://www.databaseadvisors.com/newsletters/newsletter200503/0503usingcustomcollections/using%20custom%20collections%20in%20microsoft%20access.asp
http://j-walk.com/ss/excel/tips/tip44.htm
I was just looking at something similar but not quite so detailed. I'm trying to improve the look of a complex userform by making it look more modern and was going to try to fake mouseOver highlighting or at least active/inactive shading for labels placed overtop of graphical buttons.
Anyway, have you considered just changing the names of the label objects so that they are prefixed/suffixed with some kind of group or subsystem ID?
That way when you pass them to a sub to change their colour, you can check the prefix or suffix.

Typing filename in ListBox

when I wish to type the name of a listbox item (the listbox is populated by files in a directory), for example, if I type "apples" pressing A would take me to the first object with A in it's name, but typing "p" after will take me to the first item with p as the first letter. Is there any way I can make it so I can type a few characters and it would take me to that specific item? For example, the list might have;
ability
idea
boring
typing "abi" would select ability, rather than "ability", then "boring", then "idea"
Any help is appreciated. Thanks.
I think it's possible to make System.Windows.Forms.ListBox behave like that, but it would take some non-trivial code to make it work. System.Windows.Forms.ListView has this behavior built-in, so I would suggest using a ListView instead of a ListBox.
' Hide the headers to make the ListView look like a ListBox.
Me.ListView1.View = View.Details
Me.ListView1.HeaderStyle = ColumnHeaderStyle.None
Me.ListView1.BeginUpdate()
Try
' System.Windows.Forms.ListView doesn't have data binding capability.
' The listview's items have to be added using its
' Items.Add, Items.AddRange or Items.Insert methods.
For Each filename As String In Directory.GetFiles("C:\Windows").Select(Function(s) Path.GetFileName(s))
Me.ListView1.Items.Add(filename)
Next
Finally
Me.ListView1.EndUpdate()
End Try
' Add the column after adding the items.
' Setting column width to -1 will make
' the column autosize itself to the longest item.
Dim columnHeader As New ColumnHeader
columnHeader.Width = -1
Me.ListView1.Columns.Add(columnHeader)