C# HashTable转换为DataTable 互转DataTable转换为HashTable

 #region HashTable转换为DataTable
        //========================================================================
        //  方法名称 HashTableToDataTable
        /// 
        /// HashTable转换为DataTable
        /// 
        /// 
        /// 
        /// HashTable
        /// Datatable

        public static DataTable HashTableToDataTable(Hashtable ht)
        {
            try
            {
                //创建DataTable
                DataTable dt = new DataTable();
                //创建新列
                DataColumn dc1 = dt.Columns.Add("dc1", typeof(string));
                DataColumn dc2 = dt.Columns.Add("dc2", typeof(string));

                //将HashTable中的值添加到DataTable中
                foreach (DictionaryEntry element in ht)
                {
                    DataRow dr = dt.NewRow();
                    dr["dc1"] = (string)element.Key;
                    dr["dc2"] = (string)element.Value;
                    dt.Rows.Add(dr);
                }

                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
       
        /// 
        /// DataTablez转Hashtable
        /// 
        /// 
        /// 
        public static Hashtable GetHashTable(DataTable dt)
        {
            try
            {
                if (dt != null)
                {
                    Hashtable hash = new Hashtable();
                    foreach (DataRow row in dt.Rows)
                    {
                            hash.Add(row["dc1"], row["dc2"]); 
                    }
                    return hash;
                }
                else
                {
                    return null;
                }
            }
            catch
            {
                return null;
            }
        }
        #endregion

 

你可能感兴趣的:(DataTable,HashTable,web,.net,c#)