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

Is there an easy way to convert DataTable to HashTable or SQLDataReader to HashTable ? I have to parse it through javascriptserializer. The code I use 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 gives the correct result when querying from one table in the database, but from another table that has a problem.

Is there any other way to do this?

+9
jquery c # sql sql-server-2008
source share
2 answers

You can use the following function to convert a DataTable to a 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"); 
0
source share
 public static Hashtable Fn_ConvertDataTableToHashTable(DataTable dtTable, int iRow) { Hashtable hshTable = new Hashtable(); if (CommonUtil.Fn_CheckDatatableHasValue(dtTable)) { foreach (DataColumn column in dtTable.Columns) { hshTable.Add(column.ColumnName, dtTable.Rows[iRow][column.ColumnName].ToString()); } } return hshTable; } 
-one
source share

All Articles