【问题标题】:Is it possible to build a MessageBox message that is then passed to a message box to include new lines?是否可以构建一个 MessageBox 消息,然后将其传递给消息框以包含新行?
【发布时间】:2016-12-23 23:22:42
【问题描述】:

我正在尝试为用户生成一条返回缺失清单项目列表的消息。我的问题:有没有办法构建一条消息,然后可以将其传递给包含新行的 MessageBox。我考虑过重载该方法以接受各种数量的单个消息,但必须有一种更优雅的方法来做到这一点。下面是我设计的用于处理此消息收集、显示和将来导出为更方便格式的类。

Public Class clsChecklistMissingItems

Private Shared iWrong As Integer = 0 'Number of items wrong.
Private Shared sMissingItems() As String 'Will use the number of items wrong.

Public Shared Sub CollectItem(ByVal mess As String) 'Saves the message passed to it.


    ReDim Preserve sMissingItems(iWrong) 'Resize the array based on the counter.
    sMissingItems(iWrong) = mess 'Assign the message to the missing items string array.
    iWrong = iWrong + 1 'Increment the counter (may give us +1 

End Sub

Public Sub DisplayList() 'Displays the message at the end of the execution.
    'Can this be generated procedurally?

    MessageBox.Show("There were " & iWrong & " missing or incorrect items." & vbNewLine &
                    sMissingItems(iWrong))

End Sub End Class

我的替代解决方案是编写一个格式类似于文本框的表单,其行为类似于文本框,但具有所有描述的功能。

【问题讨论】:

  • 也许会以模态形式显示具有该信息的另一个表单,以便用户在继续之前需要关闭它?
  • 不要在标题中添加“SOLVED”。您通过发布答案表明您已经解决了问题!

标签: vb.net messagebox


【解决方案1】:

使用数组不是最好的选择。 .NET 有很多内置的集合类,它们远远优于数组,比如List<T>。我知道当您来自 Visual Basic 的其他“风格”(VBScript、VBA 等)时使用数组很诱人,因为这是您所熟悉的,但您应该了解 .NET FCL 中可用的内容。

您可以使用循环和StringBuilder 来构建您的消息列表:

Dim wrongItems As New List(Of String)()

' fill the collection however you do it...
wrongItems.AddRange({"Reason 1", "Reason 2", "Reason 3"})

Dim sb As New StringBuilder()

For Each item In wrongItems
    sb.AppendLine(item)
Next

MsgBox(String.Format("There were {0} missing or incorrect items.",
                     wrongItems.Count) & vbNewLine & sb.ToString())

【讨论】:

  • 这非常有帮助。感谢您分享更好的方法。我将合并此解决方案。谢谢!
【解决方案2】:

在与我的同事交谈后,有人向我指出 VB.NET 有一个回车换行,旨在连接成一个字符串来表示一个新行。

Public Sub DisplayList()

    Dim sMessage As String = ""

    For i As Integer = 0 To sMissingItems.Length - 1
        sMessage = sMessage & sMissingItems(i) & vbCrLf
    Next

    MessageBox.Show(sMessage)

End Sub

此时我还没有机会使用列表而不是数组来实现。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-12
    • 2017-10-11
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多