Este artículo es un artículo espejo de traducción automática, por favor haga clic aquí para saltar al artículo original.

Vista: 17267|Respuesta: 0

[ASP.NET] DataTable convertido a un <Model>ejemplo genérico de clase de List

[Copiar enlace]
Publicado en 22/4/2015 9:09:58 | | |
[DBHelp] utiliza tecnología de reflexión para encapsular objetos en Listas
http://www.itsvse.com/thread-1848-1-1.html
(Fuente: Escuela Profesional de Ingeniería de Software de Wuhan)
Enlace 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
stuinfo.cs Código:
  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
test.asp.cs código:
  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
Base de datos 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


Descarga del paquete comprimido:
TestList.rar (26.89 KB, Número de descargas: 0, Precio de venta: 1 Grain MB)




Anterior:Profesionalismo "Plantilla de Plan de Carrera"
Próximo:Herramienta de suplantación de cookies veterana de Guilin
Renuncia:
Todo el software, materiales de programación o artículos publicados por Code Farmer Network son únicamente para fines de aprendizaje e investigación; El contenido anterior no se utilizará con fines comerciales o ilegales; de lo contrario, los usuarios asumirán todas las consecuencias. La información de este sitio proviene de Internet, y las disputas de derechos de autor no tienen nada que ver con este sitio. Debes eliminar completamente el contenido anterior de tu ordenador en un plazo de 24 horas desde la descarga. Si te gusta el programa, por favor apoya el software genuino, compra el registro y obtén mejores servicios genuinos. Si hay alguna infracción, por favor contáctanos por correo electrónico.

Mail To:help@itsvse.com