asp.net 010

Published on January 2017 | Categories: Documents | Downloads: 22 | Comments: 0 | Views: 233
of 11
Download PDF   Embed   Report

Comments

Content

J4ckware™ | - Curso C de ASP.NET – C# | Lección 01 10 v1.0 | Pág g. 1 de 11

Curso de ASP.NET A T - C# | Lección 010 v v1.0

Mante enim mie ento o en nN ca apa as
{ Por P Jack k Chávez z Saravi ia }
Crear la base de datos en SQL Server. S

use Master go if db_id ('leccion010') is not null d drop datab base leccion010 go -- Crea amos la base de leccion010 create database leccion010; go use leccion010; go -- Crea ar las tablas create table categorias( codigo int primary key identity(1,1), descripcion nvarchar(100) NULL, vigente e bit default 1); go insert into categorias(descripcion, vigente)values('atun', 1) insert into categorias(descripcion, vigente)values('fideos', 0) insert into categorias(descripcion, vigente)values('leche', 1) go select * from categorias
Iniciar Vi isual Studio y crear un nuevo sitio web con el no ombre de: leccion010. Crear la entidad cate egoría, para ello e clic dere echo en el sit tio web agregar nuevo o elemento… …

http://j4c ckware.blogs spot.com/

J4ckware™ | - Curso C de ASP.NET – C# | Lección 01 10 v1.0 | Pág g. 2 de 11

Al mensaje responde er afirmativa amente.

Código para p esta cla ase Entidad dCategoria. .cs

using using using using using using using using using using using

System; S S System.Data a; S System.Conf figuration; S System.Linq q; S System.Web; ; S System.Web. .Security; S System.Web. .UI; S System.Web. .UI.HtmlCon ntrols; S System.Web. .UI.WebCont trols; S System.Web. .UI.WebCont trols.WebParts; S System.Xml. .Linq;

ummary> /// <su /// Des scripción breve b de En ntidadCategoria /// </s summary> public class Enti idadCategor ria { publi ic int codi igo { get; set; } publi ic string descripcion d n { get; set; } publi ic bool vig gente { get t; set; } }
http://j4c ckware.blogs spot.com/

J4ckware™ | - Curso C de ASP.NET – C# | Lección 01 10 v1.0 | Pág g. 3 de 11 Agregar un nuevo elemento de tipo clase e con el no ombre de Funciones.c cs e implem mentar la codificac ción.

using using using using using using using using using using using using using

System; S S System.Da ta; S System.Co nfiguration; S System.Li nq; S System.We b; S System.We y; b.Security S System.We b.UI; S System.We b.UI.HtmlControls; S System.We b.UI.WebControls; S System.We b.UI.WebControls.WebParts; S System.Xm l.Linq; S System.Da ta.SqlClient; S System.Co llections.Generic;

/// <summary> /// Descripción breve de Funciones /// </summary> public static class Funciones { priva ate static string cadena = @"server=.\sqlexpr ress; database=leccion010; integrated security=true;"; public static List<EntidadCategoria> Listar() { var r lista = new List<EntidadCategoria> >(); using (var cn = new SqlConnection(cadena)) { using (var cmd = new SqlCom mmand(@"Select codigo, descr ripcion, vigente v from ca ategorias", cn)) { cn.Open(); using (var dr = cmd.ExecuteReader()) { while (dr.Read()) { var oEntidad = new EntidadCategoria(); oEntidad.codigo = Convert.ToInt32(dr["c codigo"]); oEntidad.descripcion = Convert.ToString g(dr["desc cripcion"]); oEntidad.vigente = Convert.ToBoolean(dr r["vigente e"]); lista.Add(oEntidad); oEntidad = null; } } return lista; } } } public static EntidadCategoria ObtenerCategoria(int codigo o) { var r oEntidad = new EntidadCategoria();
http://j4c ckware.blogs spot.com/

J4ckware™ | - Curso C de ASP.NET – C# | Lección 01 10 v1.0 | Pág g. 4 de 11

using (var cn = new SqlConnection(cadena)) { using (var cmd = new SqlCom mmand(@"Select codigo, descr ripcion, vigente v from ca ategorias where codigo=@cod", cn)) { cmd.Parameters.AddWithValue("cod", codigo); cn.Open(); using (var dr = cmd.ExecuteReader()) { if (dr.Read()) { oEntidad.codigo = Convert.ToInt32(dr["c codigo"]); oEntidad.descripcion = Convert.ToString g(dr["desc cripcion"]); oEntidad.vigente = Convert.ToBoolean(dr r["vigente e"]); } } return oEntidad; } } } public static bool Grabar(EntidadCategoria pEntid dad) { using (var cn = new SqlConnection(cadena)) { using (var cmd = new SqlCom mmand(@"select isnull(count(codigo),0 0) from categor rias where codigo=@ @cod or descripcion=@des", cn)) { cmd.Parameters.AddWithValue("cod", pEntidad d.codigo); cmd.Parameters.AddWithValue("des", pEntidad d.descripc cion); cmd.Parameters.AddWithValue("vig", pEntidad d.vigente); cn.Open(); if (Convert.ToInt32(cmd.ExecuteScalar()) > 0) { if (pEntidad.codigo == 0) throw new Exception("La categoria ya esta regist trado en el e sistema a, verifique los datos por favor!..."); cmd.CommandText = @"select isnull(count(c codigo),0) from categor rias where codigo<>@cod and descripcion=@des"; if (Convert.ToInt32(cmd.ExecuteScalar()) > 0) throw new Exception("No se puede grabar r un valor r duplicad do, verifique los datos por favor!..."); cmd.CommandText = @"update categorias set descripc cion=@des, vigente e=@vig where codigo=@cod"; } else cmd.CommandText = @"insert into categoria as (descripcion, vigente) values (@des, @vig)"; return Convert.ToBoolean(cmd.ExecuteNonQuer ry()); } }
http://j4c ckware.blogs spot.com/

J4ckware™ | - Curso C de ASP.NET – C# | Lección 01 10 v1.0 | Pág g. 5 de 11

} public static bool Elim minar(EntidadCategoria pEntidad) { using (var cn = new SqlConnection(cadena)) { using (var cmd = new SqlCom mmand(@"delete from m categorias where codigo=@cod", cn)) { cmd.Parameters.AddWithValue("cod", pEntidad d.codigo); cn.Open(); return Convert.ToBoolean(cmd.ExecuteNonQuer ry()); } } } }
Finalmen nte los archivos de la carpeta App_C Code serán estos: e

Insertar una tabla en n el webform m Default.asp px

http://j4c ckware.blogs spot.com/

J4ckware™ | - Curso C de ASP.NET – C# | Lección 01 10 v1.0 | Pág g. 6 de 11 Tomando como contenedor a la tabla, insert tar los siguie entes control les.

Después s de editar lo os controles, , la aparienci ia seria más o menos esto:

Selecció ón el GridView w, ingresar al a área de có ódigo y ubica ar la siguient te línea.

http://j4c ckware.blogs spot.com/

J4ckware™ | - Curso C de ASP.NET – C# | Lección 01 10 v1.0 | Pág g. 7 de 11 Ubicar estas e línea:

<Columns> <asp:BoundField DataField="descripcion" HeaderTex xt="Catego oria" /> e" /> <asp:CheckBoxField DataField="vigente" HeaderText="Vigente mns> </Colum
Una vez ubicado agr regar una nueva columna a de tipo Tem mplateField (el ( código es sta sombreado).

<Columns> <asp:TemplateField> <ItemTemplate> < href="categoria.aspx?id=<%#Eval("codigo")% <a %>">Editar r</a> </ItemTemplate> <He eaderTemplate>Editar</HeaderTemplate> </asp:TemplateField> <asp:BoundField DataField="descripcion" HeaderTex xt="Catego oria" /> <asp:CheckBoxField DataField="vigente" HeaderText="Vigente e" /> mns> </Colum
Listo. Ah hora la aparie encia será as sí:

Agregar un nuevo WebForm W al sitio web con el nom mbre de: ca ategoría.cs (insertar una tabla, agregar TextBox, Label, CheckBo ox y Button). )

http://j4c ckware.blogs spot.com/

J4ckware™ | - Curso C de ASP.NET – C# | Lección 01 10 v1.0 | Pág g. 8 de 11 Volver al webForm Default.aspx D x y seleccionar el LinkButton y editar r sus propied dades. Teng ga mucho cuidado con la prop piedad PostBackUrl (re e direcciona ará a la pág gina categor ría.aspx, env viando el

id=0)

Clic dere echo en el WebForm W Ver V código e implementar…

using using using using using using using using using using using

System; S S System.Co nfiguration; ta; S System.Da S System.Li nq; S System.We b; S System.We y; b.Security S System.We b.UI; b.UI.HtmlControls; S System.We S System.We b.UI.WebControls; b.UI.WebControls.WebParts; S System.We l.Linq; S System.Xm

public partial class _Default : System.Web.UI.Page { priva ate void LlenarDato() { try y { lblMensaje.Text = ""; g gvLista.D ataSource = null; g gvLista.D ataSource = Funciones.Listar(); g gvLista.D ataBind(); } catch (Exception ex) { lblMensaje.Text = ex.Message; }
http://j4c ckware.blogs spot.com/

J4ckware™ | - Curso C de ASP.NET – C# | Lección 01 10 v1.0 | Pág g. 9 de 11

} prote ected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) LlenarDato(); } }
Abrir el formulario f w categoría web a.aspx e imp plementar

using using using using using using using using using using using using

System; S S System.Co llections; S System.Co nfiguration; S System.Da ta; S System.Li nq; S System.We b; S System.We y; b.Security S System.We b.UI; S System.We b.UI.HtmlControls; S System.We b.UI.WebControls; S System.We b.UI.WebControls.WebParts; S System.Xm l.Linq;

e public partial class categoria : System.Web.UI.Page { priva ate void LeerData(int codigo) { lblMensaje.Text = ""; try y { v var oEntidad = Funciones.ObtenerCategoria(cod digo); txtCodigo.Text = oEntidad.codigo.ToString(); txtDescripcion.Text = oEntidad.descripcion; chkVigente.Checked = oEntidad.vigente; o oEntidad = null; } catch (Exception ex) { lblMensaje.Text = ex.Message; } }

http://j4c ckware.blogs spot.com/

J4ckw ware™ | - Cu urso de ASP P.NET – C# | Lección 010 0 v1.0 | Pág. 10 de 11

prote ected void Page_Load(object sender, EventArgs e) { txtCodigo.Enabled = false; try y { if (!Page.IsPostBack) { if (Request.Param ms["id"].ToString() == "0") txtDescripcion.Focus(); else LeerData(Convert.ToInt32(Request.Params["id"])); } } catch (Exception ex) { lblMensaje.Text = ex.Message; } } prote ected void btnAceptar_Click(object sender, Ev ventArgs e e) { lblMensaje.Text = ""; var r oEntidad = new EntidadCategoria(); oEntidad.codigo = Convert.ToInt32(Request.Param ms["id"]); oEntidad.descripcion = txtDescripcion.Text.Trim m(); oEntidad.vigente = chkVigente.Checked; try y { Funciones.Grabar(oEntidad); R Response. Redirect("default.aspx"); } catch (Exception ex) { lblMensaje.Text = ex.Message; } finally { oEntidad = null; } } prote ected void btnEliminar_Click(object sender, EventArgs e) { if (Convert.ToInt32(Request.Params["id"]) == 0) return; lblMensaje.Text = ""; var r oEntidad = new EntidadCategoria(); oEntidad.codigo = Convert.ToInt32(Request.Param ms["id"]); try y { Funciones.Eliminar(oEntidad); R Response. Redirect("default.aspx"); } catch (Exception ex) { lblMensaje.Text = ex.Message;
http://j4c ckware.blogs spot.com/

J4ckw ware™ | - Cu urso de ASP P.NET – C# | Lección 010 0 v1.0 | Pág. 11 de 11

} finally { oEntidad = null; } } prote ected void btnCancelar_Click(object sender, EventArgs e) { Response.Redirect("Default.aspx"); } }
Presione e F5 para ver rificar el corr recto funcion namiento…

A ADVERTENCIA! !! htt tp://www.safec creative.org/wor rk/13111593157 754

Curso de ASP.NET - C# C por Jack Ch hávez Saravia a.k.a. J4ckware™ ™ se encuentra bajo b una Licenc cia Creative Com mmons A Attribution Non-commercial No o Derivatives 3.0 s nombres y/o marcas m de productos utilizados s en este docum mento son mencionados únicamente con fine es de Los identific cación y son pro opiedad de sus respectivos cre eadores.

---| El autor pu uede ser con ntactado en |--e-mail: [email protected] www.fac cebook.com/j j4ckware

http://j4c ckware.blogs spot.com/

Sponsor Documents

Or use your account on DocShare.tips

Hide

Forgot your password?

Or register your new account on DocShare.tips

Hide

Lost your password? Please enter your email address. You will receive a link to create a new password.

Back to log-in

Close