求一个 DataTable 与 HashTable互转类。

yayabaobao008 2011-01-01 03:48:41
求一个 DataTable 与 HashTable互转类。
要求输入DataTable ,return为HashTable。
反之亦然。

另请问,为什么我从Excel中读取的一行数据(类似2011-1-1),在DataTable 中会自动变成时间类型的字段呢?我在代码中修改某一单元格内容,无法更新,提示我必须为datetime类型才可以。可事实上我并没有指定DT中的字段类型啊。难道从Excel读取的数据它会自动转换成相应的字段嘛??很奇怪。

迫不得已,考虑用DT 和HT相互中转一下试试看了。。。
...全文
755 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
aiyinsitan1110 2013-07-26
  • 打赏
  • 举报
回复
public static DataTable HashTableToDataTable(List<Hashtable> tableList) { DataTable dt = new DataTable(); if (tableList != null && tableList.Count > 0) { //把Key 添加到Table中 成为列名称 foreach (string item in tableList[0].Keys) { dt.Columns.Add(item, typeof(string)); } for (int i = 0; i < tableList.Count; i++) { Hashtable ht = tableList[i]; DataRow dr = dt.NewRow(); foreach (DictionaryEntry de in ht) { //把Value 添加到对应的列名下边 if (de.Value == null) dr[de.Key.ToString()] = ""; else dr[de.Key.ToString()] = de.Value.ToString(); } dt.Rows.Add(dr); } } return dt; }
mail_ricklee 2011-05-07
  • 打赏
  • 举报
回复
NickLee.Web.UI中的NickLee.Common.ODRM

参考地址www.cnblogs.com/mail-ricklee
i_devil 2011-05-07
  • 打赏
  • 举报
回复

public static Hashtable GetHashTable(DataRow row)
{
try
{
if (row!=null)
{
Hashtable hash = new Hashtable();
for (int i = 0; i < row.Table.Columns.Count; i++)
{
hash.Add(row.Table.Columns[i].ColumnName, Conver.CString(row[i]));
}
return hash;
}
else
{
return null;
}
}
catch
{
return null;
}
}


把某一行转化成Hash
srbycc 2011-05-07
  • 打赏
  • 举报
回复
#region HashTable转换为DataTable
//========================================================================
// 方法名称 HashTableToDataTable
/// <summary>
/// HashTable转换为DataTable
/// </summary>
/// <remarks>
/// </remarks>
/// <parameter>HashTable</parameter>
/// <returns>Datatable</returns>

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

链接:http://20peng1981.blog.163.com/blog/static/60003421200802103747120/
wangsong145 2011-01-01
  • 打赏
  • 举报
回复
楼主要在DataTable和HashTable之间转换也得有个转换规则吧,比如HashTable的key是什么,value怎么存储?
xixihaha_2011_098 2011-01-01
  • 打赏
  • 举报
回复
http://lwswt270.blogcn.com/diary,16568926.shtml
看一下,这个希望对你有帮助
wuyq11 2011-01-01
  • 打赏
  • 举报
回复
Hashtable ht = new Hasltable();
foreach(Datarow dr in dt)
{
ht.add(dr["a"].ToString(),dr["b"]);
}
判断重复
private void AddToht(Hashtable ht,Object Key,Object Value)
{
if(!ht.ContainsKey(Key))
{
ht.Add(Key,Value);
}
}

110,531

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧