2010-04-16 9 views
6

C'è un modo semplice per convertire un DataTable ad un HashTable o un SQLDataReader ad un HashTable? Devo analizzarlo tramite javascriptserializer. Il codice che sto usando ha qualche problema:modo semplice per convertire tabella di dati di hash table o SqlDataReader per hashtable

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; 
} 

Si sta dando un risultato corretto quando interrogato da una tabella nel database, ma da un altro tavolo sta avendo un problema.

C'è un altro modo per farlo?

+3

prega abbagliati il ​​problema, con il messaggio di errore esatto. – RedFilter

risposta

-1
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; 
} 
0

È possibile utilizzare la seguente funzione per convertire DataTable 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;  
} 

Poi nel codice basta usare,

Hashtable sendData = new Hashtable(); 
//You need to pass datatable, key field and value field 
sendData = convertDataTableToHashTable(dt, "orderNumber", "customerName"); 
Problemi correlati