String.format 问题

String.format Issues

我一直在使用 Visual basic 完成一项作业,我对打印功能并不过分熟悉,但我从参考书中了解的足够多,足以了解它们的工作原理。然而,问题似乎并不像 string.format() 函数那样与打印函数有关。出于某种原因,它的行为是不合理的,例如,一些字段彼此相邻,而另一些字段相隔几个空间。我已经尝试了一些方法,例如填充和使用等宽字体,但我仍然遇到对齐问题。我知道 header 根本没有格式化,我目前主要关心 body,因为它更加动态。数据是从一个列表框中提取的,该列表框以逗号分隔的样式格式化,并且似乎可以很好地拆分成子字符串,但是当放入一个数组然后打印预览时,很明显格式没有像我想象的那样工作。我尝试了几种不同的方法但无济于事。我敢肯定,如果需要,我可以找到解决方法,但似乎此功能应该可以使用,也许我缺少某些东西。对此事的任何帮助将不胜感激。

Private Sub mnu_file_print_Click(sender As Object, e As EventArgs) Handles mnu_file_print.Click
    PrintDocument1.Print()
End Sub

Private Sub mnu_file_print_preview_Click(sender As Object, e As EventArgs) Handles mnu_file_print_preview.Click
    PrintDocument1.DefaultPageSettings.Landscape = True
    PrintPreviewDialog1.ShowDialog()
End Sub

Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage



    Dim Record_Array(9) ' Array used to hold the for each word loop strings for inserting into the table.
    Dim int_loop_num As Integer = 0

    Dim str_print_body As String = String.Format("{0,-10}{1,-10}{2,-20}{3,-20}{4,-20}{5,-20}{6,-15}{7,-20}{8,-20}{9,-5}", Record_Array(0) & "|", Record_Array(1) & "|", Record_Array(2) & "|", Record_Array(3) & "|", Record_Array(4) & "|", Record_Array(5) & "|", Record_Array(6) & "|", Record_Array(7) & "|", Record_Array(8) & "|", Record_Array(9) & "|")

    Dim startX As Integer = 62
    Dim startY As Integer = 62

    Dim font As New Font("Courier New", 7, FontStyle.Regular)

    e.Graphics.DrawString("Room Number,Bench Number,Make,Model,Name,Serial Number,Device Description,Device Use,State Tag,Repair", lst_print_box.Font, Brushes.Black, startX, startY - 16)

    ' for each item in the list
    For Each index As String In lst_print_box.Items
        ' for each sub string in the item
        For Each word As String In Split(index, ",")
            Record_Array(int_loop_num) = word.PadRight(5, "_").PadLeft(10, "_")
            int_loop_num += 1
        Next
        str_print_body = String.Format("{0,-10}{1,-10}{2,-20}{3,-20}{4,-20}{5,-20}{6,-15}{7,-20}{8,-20}{9,-5}", Record_Array(0) & "|", Record_Array(1) & "|", Record_Array(2) & "|", Record_Array(3) & "|", Record_Array(4) & "|", Record_Array(5) & "|", Record_Array(6) & "|", Record_Array(7) & "|", Record_Array(8) & "|", Record_Array(9) & "|")

        e.Graphics.DrawString(str_print_body, font, Brushes.Black, startX, startY)
        int_loop_num = 0
        startY += lst_print_box.ItemHeight
    Next



End Sub

结果字符串中似乎有多余的空格。 检查变量 str_print_body 的内容是否有额外空格。如果有一些,您可以裁剪每个字符串,例如改变

Record_Array(2)Left(Record_Array(2), 20)

更好的方法是了解额外空格的来源并直接从源头解决问题。