Cannot use hashtable in c# application

992 views c#

Im creating an small Windows application program in c#, and using HASHTABLES i've got this error when I want to add values in a strored procedure. Error: "The non-invocable Hashtable.keys member can not be used as a method"

the error appears after hs.keys(n)

This is the code that im writting:

public int EscribirBackup(string nombre, Hashtable hs)
            SqlCommand cm = new SqlCommand();
            cm.CommandType = CommandType.StoredProcedure;
            cm.CommandText = nombre;
            for (var n = 0; n <= hs.Values.Count - 1; n++)
                cm.Parameters.AddWithValue(hs.Keys(n), hs.Values);
            cm.Connection = ABRIR("NORMAL");
            int i = cm.ExecuteNonQuery();
            return i;

answered question

don't you want hs.Keys[n] rather than hs.Keys(n)?

if i change it like that, the next error appears: you can not apply indexing with [] to an expression of type ICollection

what are you trying to do, exactly? Keys is an ICollection of the keys in the hashtable. You can't just grab one of the keys this way; you would have to convert the keys to an array. It doesn't make sense really that you are cycling through the hashtable Values.Count times, trying to add a single Key but all the Values each time.....

1 Answer


Hashtable.Keys is a collection property (member of System.Collections) which has this definition:

public virtual System.Collections.ICollection Keys { get; } 

Note that ICollection properties doesn't expose indexer, you should convert it to other collection which exposes indexer.

Hence, you should convert it to an array or List instance first, then use square brackets to access the specified index as in example below:

var keys = hs.Keys.ToArray();

for (var n = 0; n <= hs.Values.Count - 1; n++)
    cm.Parameters.AddWithValue(keys[n], hs.Values);

posted this

Have an answer?


Please login first before posting an answer.