Simon Simon - 1 year ago 64 Question

How to write the contents of a dictionary to a MessageBox

In VB.NET I want to write the contents of a dictionary to a message box.

The dictionary is rather basic

Dim x As New Dictionary(Of Integer, Users)
x.Add("1", New Users("1", "Simon"))

The user class contains 2 attributes, user ID (Integer) and Username (String).

I am struggling to write the dictionary contents. I would like to write each dictionary entry to a string but i am having no success as I keep getting the error message:

Argument 'Prompt' cannot be converted to type 'String'.

Answer Source

You are passing a string where you specified an integer:


Dim x As New Dictionary(Of Integer, Users)
x.Add(1, New Users(1, "Simon"))

Then to show the contents:

Dim sb As New StringBuilder
For Each item As KeyValuePair(Of Integer, Users) In x
  sb.AppendLine(item.Key & ") " & item.Value.ToString)

Your Users class would need to override the ToString function or change the ToString call to the property in Users that shows the user's name.

Update to Users class:

Public Class Users
  Private _p1 As Integer
  Private _p2 As String

  Sub New(ByVal p1 As Integer, ByVal p2 As String)
    _p1 = p1
    _p2 = p2
  End Sub

  Public Overrides Function ToString() As String
    Return _p2
  End Function
End Class
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download