Este artigo é um artigo espelhado de tradução automática, por favor clique aqui para ir para o artigo original.

Vista: 17267|Resposta: 0

[ASP.NET] DataTable convertido para um <Model>exemplo genérico de classe List

[Copiar link]
Publicado em 22/04/2015 09:09:58 | | |
[DBHelp] usa tecnologia de reflexão para encapsular objetos em Listas
http://www.itsvse.com/thread-1848-1-1.html
(Fonte: Faculdade Profissional de Engenharia de Software de Wuhan)
Link original:

Código DBhelp.cs
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Data.SqlClient;
  6. using System.Reflection;
  7. using System.Data;

  8. namespace TestList
  9. {
  10.     public class DBhelp
  11.     {
  12.         private static string strConn = "server=.;database=testlist;integrated security=true";

  13.         //得到一个DataTable
  14.         public static DataTable getTable(string strSql)
  15.         {
  16.             SqlConnection sqlConn = new SqlConnection(strConn);
  17.             SqlDataAdapter sqlDA = new SqlDataAdapter(strSql, sqlConn);
  18.             DataTable dt = new DataTable();
  19.             sqlDA.Fill(dt);
  20.             return dt;
  21.         }

  22.         //增删改
  23.         public static void upDateDB(string strSql)
  24.         {
  25.             SqlConnection sqlConn = new SqlConnection(strConn);
  26.             SqlCommand sqlComm = new SqlCommand(strSql, sqlConn);
  27.             sqlConn.Open();
  28.             sqlComm.ExecuteNonQuery();
  29.             sqlConn.Close();
  30.         }


  31.         //得到一个list<T>
  32.         public static List<T> getList<T>(string strSql)
  33.         {
  34.             //委托的实例化,指向packBean方法  
  35.             //PackageBean packageBean = new PackageBean(packBean);
  36.             List<T> list = new List<T>();

  37.             SqlConnection sqlConn = new SqlConnection(strConn);
  38.             SqlCommand sqlComm = new SqlCommand(strSql, sqlConn);
  39.             sqlConn.Open();
  40.             SqlDataReader sqlDR = sqlComm.ExecuteReader();

  41.             while (sqlDR.Read())
  42.             {
  43.                 //得到T的类型
  44.                 Type t = typeof(T); ;

  45.                 //查看类中的属性:
  46.                 PropertyInfo[] pis = t.GetProperties();
  47.                 // 用反射生成对象
  48.                 T model = Activator.CreateInstance<T>();
  49.                 foreach (PropertyInfo pi in pis)
  50.                 {
  51.                     if (pi != null)
  52.                     {
  53.                         //取得特定字段并赋值
  54.                         pi.SetValue(model, sqlDR[pi.Name].ToString(), null);
  55.                     }
  56.                 }

  57.                 list.Add(model);
  58.             }
  59.             sqlConn.Close();

  60.             return list;

  61.         }
  62.     }
  63. }
Copiar código
Código stuinfo.cs:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;

  5. namespace TestList
  6. {
  7.     public class stuinfo
  8.     {
  9.         public string id { get; set; }
  10.         public string name { get; set; }
  11.         public string age { get; set; }
  12.         public string live { get; set; }

  13.     }
  14. }
Copiar código
test.asp Código:
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="TestList.test" %>

  2. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  3. <html xmlns="http://www.w3.org/1999/xhtml">
  4. <head runat="server">
  5.     <title></title>
  6. </head>
  7. <body>
  8.     <form id="form1" runat="server">
  9.     <div>
  10.         <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
  11.             <Columns>
  12.                 <asp:BoundField DataField="id" HeaderText="id" />
  13.                 <asp:BoundField DataField="name" HeaderText="name" />
  14.                 <asp:BoundField DataField="age" HeaderText="age" />
  15.                 <asp:BoundField DataField="live" HeaderText="live" />
  16.             </Columns>
  17.         </asp:GridView>
  18.     </div>
  19.     </form>
  20. </body>
  21. </html>
Copiar código
Código test.asp.cs:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.UI;
  6. using System.Web.UI.WebControls;

  7. namespace TestList
  8. {
  9.     public partial class test : System.Web.UI.Page
  10.     {
  11.         protected void Page_Load(object sender, EventArgs e)
  12.         {
  13.             if (!IsPostBack) {
  14.                 List<stuinfo> stu=DBhelp.getList<stuinfo>("select * from stuinfo");

  15.                 GridView1.DataSource = stu;
  16.                 GridView1.DataBind();
  17.             }
  18.         }
  19.     }
  20. }
Copiar código
Banco de Dados SQL:
  1. create database testlist
  2. go
  3. use testlist
  4. go

  5. create table stuinfo
  6. (
  7.         id int primary key identity(1,1),
  8.         name varchar(5) not null,
  9.         age int not null,
  10.         live varchar(20) not null
  11. )
  12. go

  13. insert into stuinfo values('东方','45','地方')
  14. insert into stuinfo values('当初','47','发多个地方')
  15. insert into stuinfo values('并不','2','的方式的水电费')
  16. insert into stuinfo values('学校','11','的师傅的说法')
  17. insert into stuinfo values('形成','87','的释放速度')
  18. insert into stuinfo values('自行','45','士大夫似')

  19. select * from stuinfo
Copiar código


Pacote comprimido para download:
TestList.rar (26.89 KB, Número de downloads: 0, Preço de venda: 1 Grain MB)




Anterior:Profissionalismo "Modelo de Plano de Carreira"
Próximo:Ferramenta de falsificação de cookies para veteranos Guilin
Disclaimer:
Todo software, material de programação ou artigos publicados pela Code Farmer Network são apenas para fins de aprendizado e pesquisa; O conteúdo acima não deve ser usado para fins comerciais ou ilegais, caso contrário, os usuários terão todas as consequências. As informações deste site vêm da Internet, e disputas de direitos autorais não têm nada a ver com este site. Você deve deletar completamente o conteúdo acima do seu computador em até 24 horas após o download. Se você gosta do programa, por favor, apoie um software genuíno, compre o registro e obtenha serviços genuínos melhores. Se houver qualquer infração, por favor, entre em contato conosco por e-mail.

Mail To:help@itsvse.com