C#讀取數(shù)據(jù)庫(kù)返回泛型集合詳解(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">數(shù)據(jù)庫(kù)連接字符串</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">轉(zhuǎn)換類型</typeparam>
/// <param name="dataSet">數(shù)據(jù)源</param>
/// <param name="tableIndex">需要轉(zhuǎn)換表的索引</param>
/// /// <returns>泛型集合</returns>
public IList<T> DataSetToList<T>(DataSet dataset,int tableIndex)
{
//確認(rèn)參數(shù)有效
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++)
{
//創(chuàng)建泛型對(duì)象
T _t=Activator.CreateInstance<T>();
//獲取對(duì)象所有屬性
PropertyInfo [] propertyInfo=_t.GetType().GetProperties();
//屬性和名稱相同時(shí)則賦值
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;
}
相關(guān)文章
C#使用SQL DataAdapter數(shù)據(jù)適配代碼實(shí)例
今天小編就為大家分享一篇關(guān)于C#使用SQL DataAdapter數(shù)據(jù)適配代碼實(shí)例,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-10-10Unity的IPreprocessBuildWithReport實(shí)用案例深入解析
這篇文章主要為大家介紹了Unity的IPreprocessBuildWithReport實(shí)用案例深入解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-05-05C#傳值方式實(shí)現(xiàn)不同程序窗體間通信實(shí)例
Form2構(gòu)造函數(shù)中接收一個(gè)string類型參數(shù),即Form1中選中行的文本,將Form2的TextBox控件的Text設(shè)置為該string,即完成了Form1向Form2的傳值2013-12-12