Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 970
amby Avatar asked Jan 20 '26 05:01

amby


1 Answers

You can use the following function to convert DataTable to HashTable,

public static Hashtable convertDataTableToHashTable(DataTable dtIn,string keyField,string valueField)   
{    
   Hashtable htOut = new Hashtable();    
   foreach(DataRow drIn in dtIn.Rows)    
   {    
      htOut.Add(drIn[keyField].ToString(),drIn[valueField].ToString());    
   }   
   return htOut;    
}

Then in your code just use,

Hashtable sendData = new Hashtable();
//You need to pass datatable, key field and value field
sendData = convertDataTableToHashTable(dt, "orderNumber", "customerName");
like image 176
Abhilash Ravindran C K Avatar answered Jan 21 '26 17:01

Abhilash Ravindran C K