Sie sind auf Seite 1von 11

J4ckware | - Curso C de ASP.NET C# | Leccin 01 10 v1.0 | Pg g.

1 de 11

Curso de ASP.NET A T - C# | Leccin 010 v v1.0

Mante enim mie ento o en nN ca apa as


{ Por P Jack k Chvez 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 egora, 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# | Leccin 01 10 v1.0 | Pg g. 2 de 11

Al mensaje responde er afirmativa amente.

Cdigo 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 scripcin 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# | Leccin 01 10 v1.0 | Pg 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 cin.

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> /// Descripcin 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# | Leccin 01 10 v1.0 | Pg 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# | Leccin 01 10 v1.0 | Pg 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 sern 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# | Leccin 01 10 v1.0 | Pg g. 6 de 11 Tomando como contenedor a la tabla, insert tar los siguie entes control les.

Despus s de editar lo os controles, , la aparienci ia seria ms o menos esto:

Selecci n el GridView w, ingresar al a rea de c digo y ubica ar la siguient te lnea.

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

J4ckware | - Curso C de ASP.NET C# | Leccin 01 10 v1.0 | Pg g. 7 de 11 Ubicar estas e lnea:

<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 ( cdigo 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 ategora.cs (insertar una tabla, agregar TextBox, Label, CheckBo ox y Button). )

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

J4ckware | - Curso C de ASP.NET C# | Leccin 01 10 v1.0 | Pg 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 pg gina categor ra.aspx, env viando el

id=0)

Clic dere echo en el WebForm W Ver V cdigo 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# | Leccin 01 10 v1.0 | Pg g. 9 de 11

} prote ected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) LlenarDato(); } }


Abrir el formulario f w categora 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# | Leccin 010 0 v1.0 | Pg. 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# | Leccin 010 0 v1.0 | Pg. 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 hvez 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 cacin y son pro opiedad de sus respectivos cre eadores.

---| El autor pu uede ser con ntactado en |--e-mail: j4ckware@gmail.com www.fac cebook.com/j j4ckware

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

Das könnte Ihnen auch gefallen