C#读取数据库返回泛型集合详解(DataSetToList)
protected void page_load(object sender, eventargs e)
{
if (!ispostback)
{
ilist<lyzx.model.lyzx_newstypemodel> list = getlist<lyzx.model.lyzx_newstypemodel>(system.configuration.configurationmanager.connectionstrings["connstr"].connectionstring,
"select * from lyzx_newstype");
gridview1.datasource = list;
gridview1.databind();
}
}
public string getnewstypelink(ref string baseurl,guid newstype)
{
return "";
}
/// <summary>
/// 获取泛型集合
/// /// </summary>
/// /// <typeparam name="t">类型</typeparam>
/// /// <param name="connstr">数据库连接字符串</param>
/// <param name="sqlstr">要查询的t-sql</param>
/// <returns></returns>
public ilist<t> getlist<t>(string connstr, string sqlstr)
{
using (sqlconnection conn = new sqlconnection(connstr))
{
using (sqldataadapter sda = new sqldataadapter(sqlstr, conn))
{
dataset ds = new dataset();
sda.fill(ds);
return datasettolist<t>(ds, 0);
}
}
}
/// <summary>
/// datasettolist
/// </summary>
/// <typeparam name="t">转换类型</typeparam>
/// <param name="dataset">数据源</param>
/// <param name="tableindex">需要转换表的索引</param>
/// /// <returns>泛型集合</returns>
public ilist<t> datasettolist<t>(dataset dataset,int tableindex)
{
//确认参数有效
if (dataset==null || dataset.tables.count<=0|| tableindex<0)
{
return null;
}
datatable dt = dataset.tables[tableindex];
ilist<t> list = new list<t>();
for (int i = 0; i < dt.rows.count; i++)
{
//创建泛型对象
t _t=activator.createinstance<t>();
//获取对象所有属性
propertyinfo [] propertyinfo=_t.gettype().getproperties();
//属性和名称相同时则赋值
for (int j = 0; j < dt.columns.count; j++)
{
foreach (propertyinfo info in propertyinfo)
{
if (dt.columns[j].columnname.toupper().equals(info.name.toupper()))
{
if (dt.rows[i][j]!=dbnull.value)
{
info.setvalue(_t, dt.rows[i][j], null);
}
else
{
info.setvalue(_t, null, null);
}
break;
}
}
}
list.add(_t);
}
return list;
}
上一篇: ubuntu12.04下设置mysql显示中文乱码问题
下一篇: Oracle硬解析的几个例子