Vincent Dagpin
Vincent Dagpin

Reputation: 3611

C# Hashtable problem

i dont know what's the problem with this code.. it says string cannot be converted to object.. something like that..

//lvLogs <-- ListView (2 colums)    

Hashtable serverLogs = new Hashtable();

        serverLogs.Add("a", "aw");
        serverLogs.Add("b", "ew");
        serverLogs.Add("c", "iw");

        foreach (DictionaryEntry h in serverLogs)
        {
            lvLogs.Items.Add(h.Key).SubItems.Add(h.Value);                
        }       

but this code works fine..

Hashtable serverLogs = new Hashtable();

        serverLogs.Add("a", "aw");
        serverLogs.Add("b", "ew");
        serverLogs.Add("c", "iw");

        foreach (DictionaryEntry h in serverLogs)
        {
            //lvLogs.Items.Add(h.Key).SubItems.Add(h.Value);
            //lvi.SubItems.Add(h.Value);
            lvLogs.Items.Add(h.Key + "   -   " + h.Value);
        }       

how can i separate the key and value from the columns in lvLogs?

Upvotes: 0

Views: 508

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

First order of business, drop the Hashtable. The classes in the System.Collections namespace are obsolete and have been replaced by equivalents in the System.Collections.Generic namespace.

Use a Dictionary<string, string> instead.

Upvotes: 4

thecoop
thecoop

Reputation: 46098

Hashtable is not a strongly typed collection. DictionaryEntry.Key returns an object, and you're trying to use it as a string without a cast, which isn't allowed.

The reason the string concatentation works is that does accept object as an argument (it calls ToString() on it).

Try using Dictionary<string, string> instead.

Upvotes: 8

Related Questions