【问题标题】:Formating In Visual Basic在 Visual Basic 中格式化
【发布时间】:2020-10-26 02:03:05
【问题描述】:
 lstPrint.Items.Add(String.Format("{0,-20} {1,5}", "Denomination", "Count"))

        For x As Integer = 0 To 6
            lstPrint.Items.Add(String.Format("{0,-20} {1,13:S}", ouputArray(x), "Count"))
        Next

为了让事情变得更简单,Dim outputArray As String() = {"1$", "2$", "5$", "10$", "20$", "50$", "100$"},我交换了第二个数组,让它只是说 Count。

通常我会简单地使用Convert.ToChar(Keys.Tab) 使我的所有列对齐,但我正在尝试更好地使用字符串格式。我将如何补偿字符差异?

【问题讨论】:

  • 可以使用CustomTabOffsets 功能,同时启用UseCustomTabOffsets,根据像素位置创建制表位,如下所示:Can't make the items in a ListBox align correctly using TabStops。如果您只有一个 TabStop,请使用史蒂夫的答案。我的处理不止一个。但是,正如这里的答案所述,如果可能的话,最好用 ListView 替换 ListBox(这样你就有 real 列)。

标签: vb.net string-formatting


【解决方案1】:

如果您希望这种格式产生对齐的文本,则需要使用固定宽度的字体。空格比可变宽度字体中的其他字符窄得多。

否则,如何使用实际上具有列而不是 ListBox 的控件,例如ListView 还是 DataGridView?为工作使用最好的工具总是一个好主意。

【讨论】:

    【解决方案2】:

    我将列表框的字体设置为固定宽度的字体。接下来我得到了数组中最长字符串的长度。我使用 .PadLeft 使所有字符串的长度相同。

    Private Sub OPCode()
        ListBox1.Font = New Font("Consolas", 12)
        Dim outputArray As String() = {"1$", "2$", "5$", "10$", "20$", "50$", "100$"}
        Dim longest As Integer = outputArray.OrderByDescending(Function(s) s.Length).FirstOrDefault().Length
        For Each s In outputArray
            ListBox1.Items.Add(s.PadLeft(longest) & "    Count")
        Next
    End Sub
    

    结果:

    【讨论】:

    • 有趣,所以我的代码中有上面的 Font("Times New Roman",8) ,更改字体后,您显示的所有内容都排列整齐。知道为什么吗?
    • Times New Roman 似乎不是固定字体。 en.wikipedia.org/wiki/List_of_monospaced_typefaces
    猜你喜欢
    • 2012-08-11
    • 1970-01-01
    • 2021-12-27
    • 2021-04-24
    • 1970-01-01
    • 2019-08-18
    • 1970-01-01
    • 2013-04-05
    • 2015-11-01
    相关资源
    最近更新 更多