每行有 2 个值的组合框的任何方式? [英] Any way for a combo box with 2 values per line?

查看:18
本文介绍了每行有 2 个值的组合框的任何方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个选项,通过它我可以将组合框的功能与列表视图.

这是因为我的 SQL 查询不能有超过 1 个输出,在某些情况下我可以得到.

例如我的 SQL 表看起来有点像这样

Unique_ID - 名称
123456789 - 西蒙
987654321 - 西蒙

基本上同一个名字可以在数据库中多次出现,每个条目都有自己的ID.

为了用户,我不能让他们根据 ID 选择要编辑的记录,而是让他们根据名称选择记录.但是,当我的查询产生超过 1 条记录时,我会收到 MySQL 异常.

这是有问题的 MySQL 查询:
"SELECT worldspace fromsurvivor where is_dead = '0' _ and resume.unique_id = (select unique_id from profile where name = '" & target & "')"

该查询的输出然后用于另一个 UPDATE 查询.

那么,我的组合框是否有可能同时拥有 ID &名称作为值,它们之间有明确的分隔,因此整个值保持良好的可读性,就像在列表视图元素中一样?

解决方案

我看到您已经获得了 HighCore 的处理方式,即 WPF 中的一切都非常简单,而 WinForms 有多么糟糕.但是您可能有兴趣知道您也可以在 WinForms 中执行此操作.你只是做的有点不同.WinForms 和 WPF 中的标准设计习惯用法不同也就不足为奇了;这并不能证明一个比另一个更好",这只是意味着您需要学习如何使用您正在使用的那个.(虽然,诚然,使用 20 年前与 Windows 本身一起发明的 UI 框架来实现一些更高级的东西要困难一些.它确实拥有的功能相当出色.)>

格式化信息有两种基本方式:一行上的所有内容(我相信这就是您在问题中要求的内容)或两行上的信息片段,其中每个项目基本上是一个两行单元(这就是 HighCore 的 WPF 解决方案所展示的.

单行格式

简单化的方法

我们将首先考虑将所有内容放在一行中,这确实很简单.您不需要用于分隔的列,您可以在将项目添加到组合框时使用某种独特的分隔符,例如竖线 (|) 或破折号 (-) 就像您在问题中使用的那样.

这很有效,因为 ComboBox.Items.Add 方法接受 Object 类型的参数,它只调用 ToString获取控件中显示的值.如果你给它传递一个字符串,它会显示那个字符串.

myComboBox.BeginUpdate()对于 myRecordSet 中的每条记录myComboBox.Items.Add(String.Format("{0} | {1}", record.UniqueID, record.Name))' 甚至...myComboBox.Items.Add(String.Format("{0} ({1})", record.UniqueID, record.Name))下一条记录myComboBox.EndUpdate()

        ;   或

通过 OOP 的增量改进

您甚至可以将自定义类传递给 Add 方法,该方法跟踪唯一 ID 和名称属性(以及您想要的任何其他内容)并覆盖 ToString 方法用于显示目的.

公开课记录公共属性 UniqueID As Long ' 也许这也应该是一个字符串公共属性名称作为字符串公共覆盖函数 ToString() 作为字符串'为此生成将在组合框中显示的字符串' 记录,就像我们在上面直接将其添加到组合框时所做的那样,' 除了在这种情况下,它将动态生成,' 允许您还跟踪每个项目的状态信息.返回 String.Format("{0} | {1}", Me.UniqueID, Me.Name)结束函数结束班' ...' (在其他地方,当您将项目添加到组合框时:)myComboBox.BeginUpdate()对于 myRecordSet 中的每个 r' 创建一个表示此项的 Record 对象,并设置其属性.将新记录调暗为新记录newRecord.UniqueID = r.UniqueIDnewRecord.Name = r.Name' ...等等.' 然后,将该对象添加到组合框.myComboBox.Items.Add(newRecord)下一个myComboBox.EndUpdate()

修复锯齿

当然,如果每组中的第一项可以是可变长度的,并且您使用的是可变宽度字体(即,不是像地球上除代码编辑器之外的每个 UI 那样等宽的字体),则分隔符获胜不排队,你不会得到两个格式很好的列.相反,它看起来很混乱和丑陋.

ComboBox 控件支持制表符会很好,它可以自动为我们处理所有内容,但不幸的是它没有.遗憾的是,这是底层 Win32 控件的硬性限制.

解决这个边缘参差不齐的问题是可能的,但它确实变得有点复杂.它需要接管组合框中项目的绘制,称为所有者绘制".

为此,您将其 DrawMode 属性设置为 OwnerDrawFixed 并处理 属性为其正常值的两倍,因为您将有两行.您可以使用 TextRenderer.MeasureText 以复杂的方式完成此操作,也可以通过将默认值乘以 2 来轻松完成此操作.我在本演示中选择了后者.

将此类添加到您的项目中,然后使用MultiLineComboBox控件代替内置的System.Windows.Forms.ComboBox.所有的属性和方法都一样.

公共类 MultiLineComboBox :继承 ComboBox公共子新建()' 调用基类.MyBase.New()' 在这个组合框中输入一个值是没有意义的,所以让它不可能.Me.DropDownStyle = ComboBoxStyle.DropDownList' 将每个项目的高度设置为其正常值的两倍'(因为我们有两行而不是一行).我.ItemHeight *= 2结束子Protected Overrides Sub OnDrawItem(e As DrawItemEventArgs)' 调用基类.MyBase.OnDrawItem(e)' 填充背景.e.DrawBackground()' 提取与要绘制的组合框项对应的 Record 对象.如果 (e.Index >= 0) 那么Dim record As Record = DirectCast(Me.Items(e.Index), Record)' 格式化项目的标题字符串.Dim caption As String = String.Format("ID: {0}{1}Name: {2}", record.UniqueID.ToString(), Environment.NewLine, record.Name)' 然后绘制该字符串,左对齐并垂直居中.TextRenderer.DrawText(e.Graphics, caption, e.Font, e.Bounds, e.ForeColor, TextFormatFlags.Left 或 TextFormatFlags.VerticalCenter)万一' 最后,绘制焦点矩形.e.DrawFocusRectangle()结束子结束班

添加幻想和繁荣

我们现在得到的还不错,但是通过在 OnDrawItem 中的绘图代码上付出更多努力,我们可以添加一些额外的视觉幻想和繁荣.

例如,如果没有选择矩形,就很难判断这些实际上是两行单位.这对于组合框控件来说是不寻常的,因此出于可用性原因,您的应用程序应该竭尽全力使这一点非常清楚.我们可以这样做的一种方法是缩进第二行.您还记得我说过内置组合框控件不支持选项卡吗?好吧,这不再适用,因为我们现在自己在画图.我们可以通过在第二行的开头添加一些额外的填充来模拟制表符.

如果您希望标签(ID:"和名称:")与实际值分开设置,您也可以这样做.也许您可以将标签加粗并淡化文本颜色.

所以您会看到,只需使用绘图代码,您就可以创建几乎任何您想要的效果.我们拥有完全的控制权,并且通过将其全部包装在一个可以在任何地方重复使用的 MultiLineComboBox 类中,您的其余代码甚至不必知道正在发生任何特殊情况.很酷吧?

避免所有的工作

最后,如果我没有指出您可以跳过所有这些工作并且选择各种已经编写好的自定义多行组合框控件.

这个非常漂亮.当您单击组合框上的下拉箭头时,它实际上只是显示一个 ListView 控件.通过这样做,您可以免费获得 ListView 控件的所有格式细节,但它的行为就像一个普通的 ComboBox.

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.

这篇关于每行有 2 个值的组合框的任何方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆