Operación Edit, Delete, Update e Insert en un DataGrid: Parte I



Documentos relacionados
TEMA 4: FLUJO DE UNA APLICACIÓN

Introducción a ASP.NET

Tutorial : Hacer Combos Dependientes tipo Departamento Ciudad en ASP. Net

UNIVERSIDAD DON BOSCO FACULTAD DE ESTUDIOS TECNOLÓGICOS COORDINACION DE COMPUTACIÓN

ANEXOS IMPLEMENTACIÓN DE MOVIMIENTOS SUAVES EN

Desarrollo de aplicaciones web con LAMP.NET (Linux,Apache,Mono y PostgreSQL) Parte III de III

UNIVERSIDAD DON BOSCO FACULTAD DE ESTUDIOS TECNOLÓGICOS ESCUELA DE COMPUTACIÓN

Adrián Hurtado González Cristóbal Miranda Puente. Departamento de Ingeniería Telemática Universidad Carlos III de Madrid

Objetivo. Metodología. Aplicaciones Web Herencia Visual Master Page File. Lorena Castañeda Bueno Laboratorio de programación Página 1 de 7

3.- Desarrollo e implementación del sistema.

GUÍA DE TRABAJO N 11 LENGUAJE C# Programación de Software Articulación SENA Grado 10 Ing. Néstor Raúl Suarez Perpiñan Página 2 de 11

UNIVERSIDAD DON BOSCO FACULTAD DE ESTUDIOS TECNOLÓGICOS COORDINACION DE COMPUTACIÓN

Practica 7 Conexión a su base de datos. Optativa II

Desarrollo de WebParts

Curso.NET con C# Módulo 1 / Página 1. Servicio de Informática

Marcos de Desarrollo. Diseño e implementación de aplicaciones Web con.net

Tutorial para la creación de un sitio Web con un formulario ASP.NET

Curso.NET con C# Modulo 2 / Página 1. Servicio de Informática

Un poco de culturilla...1 Crear un servicio Web...1 Usar servicios web...6

Día 2: Utilizando controles de datos en Visual Studio 2008.

UNIVERSIDAD DON BOSCO FACULTAD DE ESTUDIOS TECNOLÓGICOS COORDINACION DE COMPUTACIÓN

UNIVERSIDAD DON BOSCO FACULTAD DE ESTUDIOS TECNOLÓGICOS ESCUELA DE COMPUTACIÓN

TECNOLOGÍAS DE LA INFORMACIÓN APLICADAS AL DERECHO INMOBILIARIO REGISTRAL JURÍDICO ANEXO 1 DIAGRAMA ENTIDAD RELACIÓN

Creación de un sistema ABC

Agregar código a un formulario Web Form con Microsoft ASP.NET

ASP.NET. Controles HTML y ASP.NET de Servidor.

UNIVERSIDAD DON BOSCO FACULTAD DE ESTUDIOS TECNOLÓGICOS COORDINACION DE COMPUTACIÓN

TEMA 5: Trabajando con bases de datos. ClaseOracleBD

GUIA PRACTICA 1 VISUAL C#.Net SQL SERVER 2012 MANTENIMIENTO DE UNA TABLA

Manejo de una Base de Datos Microsoft SQL Server. a través de Visual C #, vía instrucciones SQL.

Web Forms. Integración de Sistemas. Parte II. Diseño e implementación de aplicaciones Web con.net

Conexión SQL Server y C# (Consola)

Para instalar la radio en la PC sólo se tiene que seguir estos paso.

UNIVERSIDAD DON BOSCO FACULTAD DE ESTUDIOS TECNOLÓGICOS COORDINACION DE COMPUTACION GUIA DE LABORATORIO #14

ELABORACIÓN DE PÁGINAS WEB. CBTIS No. 02 ISC. RICARDO GARCÍA LÓPEZ

Programació amb C#.NET

SADCG SADCG. Sistema de Administración y Distribución de Contenidos Gráficos. Estándares de Programación

1. crear la base de datos BANCO, dentro de ella crear las siguientes tablas y establecer la siguiente relación.

Programación de Aplicaciones Visuales II Ejercicio Paso a Paso: Aplicación para HelpDesk

I.- Objetivo. II.- Introducción

Programación avanzada en.net con C# Servicio de Informática GRID VIEW

GUÍA DE TRABAJO GRADO 11. Articulación SENA Programación de Software Ing. Néstor Raúl Suarez Perpiñan Página 1 de 6

ASP.NET. Controles ASP.NET de validación.

GUÍA DE TRABAJO N 7 LENGUAJE C# Educación Media Fortalecida Programación de Software Grado 11 Ing. Néstor Raúl Suarez Perpiñan Página 1 de 8

ASP.NET. Introducción a las aplicaciones Web.

Acceso a Datos. Visual Basic.NET 2005

GUÍA DE TRABAJO GRADO 11 Programación de. Software Ing. Néstor Raúl Suarez Perpiñan Página 1 de 8

Manual de JSP con MySQL

La plantilla propone aprovechar esta estructura en común y sólo modificar el contenido del área del documento que sea diferente.

ADO.NET con Base de datos SQL Server

MANUAL DE CREACION DE FORMULARIOS PARTE 1. Este manual tiene como finalidad explicar como se pueden crear los formularios sencillos de un proyecto.

Quieres diseñar una página web y no sabes por dónde empezar? Puedes decantarte por utilizar Visual Web Developer.

Bases de Datos Access y C#. Insert, select, update, delete. 1. Crea una base de Datos en Access

Curso.NET con C# Modulo 3 / Página 1. Servicio de Informática

Universidad Autónoma Metropolitana Iztapalapa División de Ciencias Básicas e Ingeniería

Conectar Flash con Access usando MDM Zinc

Tema: Conexión a Base de Datos.

Componentes de una aplicación ASP.NET

Objetivo. Metodología. Aplicaciones Web Controles avanzados. Control: Multiview/View

Mecanismos de acceso a datos usando ADO.NET

Programación de Aplicaciones Visuales II Ejercicio Paso a Paso: Aplicación para HelpDesk

Anexo de documentación

Programación de Consultas SQL ADO.Net LDP / DUOC-AV

UNIVERSIDAD DON BOSCO FACULTAD DE ESTUDIOS TECNOLÓGICOS ESCUELA DE COMPUTACIÓN

44 Desarrollo Profesional de Aplicaciones con C# Formularios en ASP.NET...45 Ejecución de páginas ASP.NET Creación de páginas ASP.NET...

Manual de uso del Taglib de Template Saga

Programación Gambas 3 Prof: Mileti, P. Acceso a base de datos SQLite desde Gambas 3.

Usando Web Services de Q-flow

Guía práctica del modulo de Creación de Aplicaciones WEB

GUÍA DE TRABAJO GRADO 11 Programación de. Software Ing. Néstor Raúl Suarez Perpiñan Página 1 de 6

Capitulo 1: Comprender Microsoft Web Technologies

Manual de Integrador.NET

Acceso a Base de Datos

Tutorial 4. Aplicaciones Web con NetBeans 5.0

Práctica sobre compartición de instancias remotas.

Uso de Menú en Visual Basic Studio.NET Implementación de Menú con Crystal Report en Studio.Net Prof. Giovanni Francisco Sáenz Araica.

Introducción para el programador de SharePoint. Laboratorio práctico. Manual del laboratorio SPCHOL200 Generar elementos web visuales C#

GALA. ADO Modo Conectado. Modelo de Base de Datos Relacional. m018a Curso Manejo de Datos con Visual Basic 2010, 24 h

Controles en ASP.NET

Crear un formulario Web Form con Microsoft ASP.NET. ALAN IGNACIO SEPÚLVEDA RODRIGUEZ

TUTORIAL APLICACIONES EVOLUTION CON ACTIVEX EVOLINK

Marcos de Desarrollo. Diseño e implementación de aplicaciones Web con.net

Prof. Giovanni Francisco Sáenz Araica.

1. Bases de datos desde VB.Net 1.1 Introducción. Desde Vb Net 2005 se puede acceder a las siguientes bases de datos, utilizando las clases adecuadas.

Trabajar con las fuentes de datos y controles vinculados de ASP.NET 2.0

Conociendo el ambiente de programación de Java. M. en C. Erika Vilches

Creación de controles de usuario

Lazarus Free Pascal Compiler

JUSTIFICACIÓN DE LA PROPUESTA

UNIVERSIDAD LIBRE DE COLOMBIA FACULTAD INGENIERIA DE SISTEMAS ELECTIVA TECNICA II.NET Y SQL SERVER

Conexión a Base de Datos.

Código fuente C# Código asociado al formulario Splash

ATLAS MANUAL DE USUARIO COMPONENTE CODIGO DE BARRAS

Transcripción:

Operación Edit, Delete, Update e Insert en un DataGrid: Parte I Si va a utilizar un DataGrid entonces necesitarás usar los edit, update, delete con los datos en un DataGrid. Suponiendo que en la tabla la cual los datos estarán utilizándose en los DataGrid, esos entonces contendrán varios recordos en un página los cuales no se podrán visualuzarlos, entonces se pueden desplegar haciendo roles en un DataGrid. Este artículo se presentará cómo usar los edit, delete and update data en un DataGrid para presentarlos en la página. Este es el código aspx: Aquí estña el contenido de cómo se diseñó el web form. Utilizamos un DataGrid en el webform. Aquí configuramos las propiedades que necesitamos emplear en la operación con el DataGrid. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Debug="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>edit Update Cancel In DataGrid</title> </head> <body> <form id="form1" runat="server"> <div> <asp:datagrid ID="gridedit" runat="server" DataKeyField="id" BorderStyle="Ridge" GridLines="None" BorderWidth="2px" BorderColor="White" BackColor="White" CellPadding="3" CellSpacing="1" AllowSorting="True" PagerStyle- HorizontalAlign="Center" HorizontalAlign="Left" OnEditCommand="editgrid_click" OnCancelCommand="gridcancel_click" OnPageIndexChanged="gridedit_PageIndexChanged" OnUpdateCommand="updategrid_UpdateCommand" Height="267px" PageSize=5 AllowPaging="true" OnDeleteCommand="gridedit_DeleteCommand" AutoGenerateColumns="false" Width="50%"> <FooterStyle ForeColor="Black" BackColor="#C6C3C6"></FooterStyle> <HeaderStyle Font-Bold="True" ForeColor="#FFFFFF" BackColor="#A53A6A"></HeaderStyle> <FooterStyle BackColor="beige" /> <PagerStyle Font-Bold="true" Mode=NumericPages Font-Underline="true"/> <Columns> <asp:boundcolumn DataField=id HeaderText="ID"> <ItemStyle BackColor="graytext" />

<HeaderStyle BackColor="graytext" /> <asp:boundcolumn DataField=name HeaderText="Name"> <asp:boundcolumn DataField=F_name HeaderText="F_Name"> <asp:boundcolumn DataField=l_name HeaderText="L_Name"> <asp:boundcolumn DataField=City HeaderText="City"> <asp:boundcolumn DataField=State HeaderText="State"> <asp:editcommandcolumn CancelText="Cancel" EditText="Edit" UpdateText="Update" HeaderText="Edit"> </asp:editcommandcolumn> <asp:buttoncolumn CommandName="Delete" HeaderText="Delete" Text="Delete"> </asp:buttoncolumn> </Columns> </asp:datagrid> </div> </form> </body> </html>

Con este código de aspx el web form podría verse así: Figure 1 Este es el código fuente: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page SqlDataAdapter da; DataSet ds = new DataSet(); SqlConnection con; SqlCommand cmd = new SqlCommand(); protected void Page_Load(object sender, EventArgs e) if (!Page.IsPostBack)

// Define the Edit Command public void editgrid_click(object sender, DataGridCommandEventArgs e) gridedit.edititemindex = e.item.itemindex; // Define the Cancel Command public void gridcancel_click(object sender, DataGridCommandEventArgs e) gridedit.edititemindex = -1; //Here we Bind the data public void Binddata() con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]); cmd.commandtext="select * from record"; cmd.connection = con; da = new SqlDataAdapter(cmd); da.fill(ds); con.open(); gridedit.datasource = ds; gridedit.databind(); con.close(); //Update Command Defination protected void updategrid_updatecommand(object source, DataGridCommandEventArgs e) con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]); cmd.commandtext = "Update record set name=@name,f_name=@f_name, l_name=@l_name,city=@city,state=@state where id=@id"; cmd.parameters.add("@name", SqlDbType.Char).Value = ((TextBox)e.Item.Cells

[1].Controls[0]).Text; cmd.parameters.add("@f_name", SqlDbType.Char).Value = ((TextBox)e.Item.Cells [2].Controls[0]).Text; cmd.parameters.add("@l_name", SqlDbType.Char).Value = ((TextBox)e.Item.Cells [3].Controls[0]).Text; cmd.parameters.add("@city", SqlDbType.Char).Value = ((TextBox)e.Item.Cells [4].Controls[0]).Text; cmd.parameters.add("@state", SqlDbType.Char).Value = ((TextBox)e.Item.Cells [5].Controls[0]).Text; cmd.parameters.add("@id", SqlDbType.Int).Value = gridedit.datakeys [e.item.itemindex]; cmd.connection = con; cmd.connection.open(); cmd.connection.close(); gridedit.edititemindex = -1; // Delete Command Defination public void gridedit_deletecommand(object sender, DataGridCommandEventArgs e) con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]); int U_ID = (int)gridedit.datakeys[(int)e.item.itemindex]; cmd.commandtext = " Delete from record where id=" + U_ID; cmd.connection = con; cmd.connection.open(); cmd.connection.close(); gridedit.edititemindex = -1; // For Paging public void gridedit_pageindexchanged(object source, DataGridPageChangedEventArgs e) gridedit.currentpageindex = e.newpageindex;

Cuando ejecutamos el proyecto, podremos verlo así: Figure 2

Si le damos click al Edit entonces podemos mirarlo de la siguiente forma: Figure 3

Operación Edit, Delete, Update e Insert en un DataGrid: Parte II En el artículo anterior se explicó cómo emplear edit, delete y update a los records en el DataGrid. Ahora se explicará cómo utilizar el insert en un nuevo record en un DataGrid. Este es el código aspx: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" Debug="true" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>edit Update Delete Cancel and Insert In DataGrid</title> </head> <body> <form id="form1" runat="server"> <div> <asp:datagrid ID="gridedit" runat="server" Width="100px" DataKeyField="id" BorderStyle="Ridge" GridLines="None" BorderWidth="2px" BorderColor="White" BackColor="White" CellPadding="3" CellSpacing="1" AllowSorting="True" PagerStyle-HorizontalAlign="Center" HorizontalAlign="Left" OnEditCommand="editgrid_click" OnCancelCommand= "gridcancel_click" OnPageIndexChanged= "gridedit_pageindexchanged" OnUpdateCommand="updategrid_UpdateCommand" Height="267px" PageSize=5 AllowPaging="true" OnDeleteCommand="gridedit_DeleteCommand" AutoGenerateColumns="false" SelectedItemStyle-Width="100px"> <FooterStyle ForeColor="Black" BackColor="#C6C3C6"></FooterStyle> <HeaderStyle Font-Bold="True" ForeColor="#FFFFFF" BackColor="#A53A6A"></HeaderStyle> <FooterStyle BackColor="beige" /> <PagerStyle Font-Bold="true" Mode=NumericPages Font-Underline="true"/> <Columns> <asp:boundcolumn DataField=id HeaderText="ID" ItemStyle-Width="10px" Visible="false"> <ItemStyle BackColor="graytext" /> <HeaderStyle BackColor="graytext" /> <asp:boundcolumn DataField=name HeaderText="Name">

<asp:boundcolumn DataField=F_name HeaderText="F_Name"> <asp:boundcolumn DataField=l_name HeaderText="L_Name"> <asp:boundcolumn DataField=City HeaderText="City"> <asp:boundcolumn DataField=State HeaderText="State"> <asp:editcommandcolumn CancelText="Cancel" EditText="Edit" UpdateText="Update" HeaderText="Edit"> </asp:editcommandcolumn> <asp:buttoncolumn CommandName="Delete" HeaderText="Delete" Text="Delete"> </asp:buttoncolumn> </Columns> </asp:datagrid> <br /><br /> <asp:button ID="btninsert" runat="server" Text="Click Here to Insert a New record" Width="250px" OnClick="InsertNewRecord_click" /><br /><br /> <asp:label ID="lblnewname" runat="server" Width="120px" Text="Enter Name" Visible="false"></asp:Label> <asp:textbox ID="txtnewname" runat="server" Visible="false"></asp:TextBox><br /><br /> <asp:label ID="lblF_name" runat="server" Width="120px" Text="Enter Father Name" Visible="false"></asp:Label> <asp:textbox ID="txtF_name" runat="server" Visible="false" ></asp:textbox> <br /><br /> <asp:label ID="lblLast_name" runat="server" Width="120px" Text="Enter Last Name" Visible="false"></asp:Label> <asp:textbox ID="txtLast_Nmae" runat="server" Visible="false"></asp:TextBox> <br /><br /> <asp:label ID="lblcity" runat="server" Text="Enter city" Width="120px" Visible="false"></asp:Label>

<asp:textbox ID="txtcity" runat="server" Visible="false"></asp:TextBox> <br /><br /> <asp:label ID="lblState" runat="server" Width="120px" Text="Enter State Name" Visible="false"></asp:Label> <asp:textbox ID="txtState" runat="server" Visible="false"></asp:TextBox> <asp:button ID="btnnewRecordSubmit" runat="server" Text="Insert" OnClick="Submitnew" Width="100px" Visible="false" /> </div> </form> </body> </html> La aplicación de aspx se vería así: Figure 1: El diseño de la Aplicación. Se configura la propiedad visible de todas los label, textbox e insert button en False. Todos estos estarán visible cuando se le de click en Insert como un Nuevo record button. El código fuente se ve así: using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page SqlDataAdapter da;

DataSet ds = new DataSet(); SqlConnection con; SqlCommand cmd = new SqlCommand(); protected void Page_Load(object sender, EventArgs e) if (!Page.IsPostBack) // Define the Edit Command public void editgrid_click(object sender, DataGridCommandEventArgs e) gridedit.edititemindex = e.item.itemindex; // Define the Cancel Command public void gridcancel_click(object sender, DataGridCommandEventArgs e) gridedit.edititemindex = -1; //Here we Bind the data public void Binddata() con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]); cmd.commandtext="select * from record order by id Asc"; cmd.connection = con; da = new SqlDataAdapter(cmd); da.fill(ds); con.open(); gridedit.datasource = ds; gridedit.databind(); con.close(); //Update Command Defination protected void updategrid_updatecommand(object source, DataGridCommandEventArgs e) try con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]); cmd.commandtext = "Update record set name=@name,f_name=@f_name, l_name=@l_name,city=@city,state=@state where id=@id";

cmd.parameters.add("@name", SqlDbType.Char).Value = ((TextBox)e.Item.Cells[1].Controls[0]).Text; cmd.parameters.add("@f_name", SqlDbType.Char).Value = ((TextBox)e.Item.Cells[2].Controls[0]).Text; cmd.parameters.add("@l_name", SqlDbType.Char).Value = ((TextBox)e.Item.Cells[3].Controls[0]).Text; cmd.parameters.add("@city", SqlDbType.Char).Value = ((TextBox)e.Item.Cells[4].Controls[0]).Text; cmd.parameters.add("@state", SqlDbType.Char).Value = ((TextBox)e.Item.Cells[5].Controls[0]).Text; cmd.parameters.add("@id", SqlDbType.Int).Value = gridedit.datakeys[e.item.itemindex]; cmd.connection = con; cmd.connection.open(); cmd.connection.close(); gridedit.edititemindex = -1; catch (Exception ex) Response.Write(ex.Message); // Delete Command Defination public void gridedit_deletecommand(object sender, DataGridCommandEventArgs e) con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]); int U_ID = (int)gridedit.datakeys[(int)e.item.itemindex]; cmd.commandtext = " Delete from record where id=" + U_ID; cmd.connection = con; cmd.connection.open(); cmd.connection.close(); gridedit.edititemindex = -1; // For Paging public void gridedit_pageindexchanged(object source, DataGridPageChangedEventArgs e)

gridedit.currentpageindex = e.newpageindex; //Link for Insert a new Record in a table public void InsertNewRecord_click(object source, System.EventArgs e) lblnewname.visible = true; txtnewname.visible = true; lblf_name.visible = true; txtf_name.visible = true; lbllast_name.visible = true; txtlast_nmae.visible = true; lblcity.visible = true; txtcity.visible = true; lblstate.visible = true; txtstate.visible = true; btnnewrecordsubmit.visible = true; // Command for insert a new Record public void Submitnew(object source, System.EventArgs e) con = new SqlConnection(ConfigurationSettings.AppSettings["connect"]); cmd.commandtext = "insert into record(name,f_name,l_name,city,state) values(@name,@f_name,@l_name,@city,@state)"; cmd.parameters.add("@name", SqlDbType.Char).Value = txtnewname.text; cmd.parameters.add("@f_name", SqlDbType.Char).Value = txtf_name.text; cmd.parameters.add("@l_name", SqlDbType.Char).Value = txtlast_nmae.text; cmd.parameters.add("@city", SqlDbType.Char).Value = txtcity.text; cmd.parameters.add("@state", SqlDbType.Char).Value = txtstate.text; cmd.connection = con; cmd.connection.open(); cmd.connection.close(); gridedit.edititemindex = -1; txtnewname.text = ""; txtf_name.text = ""; txtlast_nmae.text = ""; txtcity.text = ""; txtstate.text = ""; lblnewname.visible = false; txtnewname.visible = false; lblf_name.visible = false; txtf_name.visible = false; lbllast_name.visible = false; txtlast_nmae.visible = false; lblcity.visible = false;

txtcity.visible = false; lblstate.visible = false; txtstate.visible = false; btnnewrecordsubmit.visible = false; Ahora cuando el User ejecutará el proyecto la venta se verá así: Figure 2: In running State Project. Supuestamente si el usuario desea insertar un nuevo record, entonces tundra que hacer click en el butón "Click Here" para insertar u nuevo record. Onclick del button, la nueva ventana se verá así:

Figure 3: Insertar un Nuevo Record. Cuando el usuario clickeé en el butón insertar entonces el record se insertará en el DataGrid. Figure 4: Record Insertado.