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?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With