mardi 5 juillet 2016

Easy way to convert data table to hash table or sqldatareader to hashtable

Is there an easy way to convert a DataTable to a HashTable or a SQLDataReader to a HashTable? I have to parse it through javascriptserializer. The code I am using has some problems:

try
{
    using (SqlConnection conn = new SqlConnection(ConnectionString))
    {
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
            dt.Load(dr);
        }
    }

    Hashtable sendData = new Hashtable();

    foreach (DataRow drIn in dt.Rows)
    {

        sendData.Add(drIn["orderNumber"].ToString(), drIn["customerName"].ToString());

    }

    sendData.Add("orderNum", order);
    JavaScriptSerializer jss = new JavaScriptSerializer();
    string output = jss.Serialize(sendData);
    return output;
}
catch (Exception ex)
{
    return ex.Message + "-" + ex.StackTrace;
}

It is giving a correct result when queried from one table in the database but from another table it's having a problem.

Is there any other way to do this?

Aucun commentaire:

Enregistrer un commentaire