Pop

41-. Aplicaciones web.GridView.Carrito de compra(4).Curso de C# con Visual Studio 2017.

41-. Aplicaciones web.GridView.Carrito de compra(4)

   - En este capítulo del curso de programación en c# con visual studio 2017,vamos a utilizar el control GridView y el objeto DataTable. En el objeto DataTable iremos almacenando los productos y las cantidades seleccionadas, para posteriormente validar contra nuestra base de datos que estos productos existen.Una vez comprobado que estos productos existen los mostramos al usuario en el control GridView 

-   Os dejo unas pinceladas de estos dos controles y unos enlaces a la MSDN:

  • DataTable: Un objeto DataTable representa una tabla de datos relacionales de la memoria; los datos son locales de la aplicación basada en .NET en la que residen, pero se pueden llenar desde un origen de datos como Microsoft SQL Server.(Más información)

  • GridView:Muestra los valores de un origen de datos en una tabla en la que cada columna representa un campo y cada fila representa un registro. El control GridView le permite seleccionar, ordenar y editar estos elementos.(Más información)
  

-  Os dejo el código SQL y el código de la página de la aplicación vista en el video:

  • Procedimiento alamcenado SQL al que llamamamos para cargar el Gridview:
CREATE PROCEDURE [dbo].[DameDatosProductos]
   
    @Lista AS dbo.ListaProductosCompra READONLY
AS
BEGIN



        DECLARE @TablaTemp2 TABLE(IdTemp int NOT NULL, cantidad int)
        INSERT INTO @TablaTemp2 SELECT idprodcuto,cantidad FROM @lista

        SELECT IdProducto,Nombre,PrecioVenta,t.cantidad,Descripcion
        FROM Productos
        INNER JOIN @TablaTemp2 as t ON t.IdTemp = Productos.idproducto
      
 END

  •  Código de la página pedidos.aspx:
 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Pedidos.aspx.cs" Inherits="GestionVarios.Pedidos" MasterPageFile="~/Master.Master" %>

<asp:Content ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <div style="background-color: #FFFFFF">
        <table>
            <tr>
                <td align="left" width="30%">
                    <asp:TreeView ID="treeViewProductos" runat="server" OnSelectedNodeChanged="treeViewProductos_SelectedNodeChanged"></asp:TreeView>

                </td>
                <td align="center"  width="50%">
                   
                    <asp:Label ID="lblNombreProducto" runat="server"></asp:Label><br />
                    <asp:Label ID="lblDescripcion" runat="server"></asp:Label><br />
                    <asp:Label ID="lblPrecioDeCompra" runat="server"></asp:Label><br />
                    <asp:Label ID="lblCantidad" runat="server" Text="Unidades:" Visible="false"></asp:Label>
                    <asp:TextBox runat="server" ID="txtUnidades" Width="40px" Visible="false"></asp:TextBox>
                      <asp:RequiredFieldValidator ID="mreqEMail" runat="server" ControlToValidate="txtUnidades" ErrorMessage="*" Display="Dynamic" ForeColor="Red"  ></asp:RequiredFieldValidator><br />
                    <asp:RegularExpressionValidator ID="mregEMail" runat="server" ControlToValidate="txtUnidades" ErrorMessage="Introduzca un numero" ValidationExpression="^\d+$" Display="Dynamic"  ForeColor="Red"></asp:RegularExpressionValidator>
      
                  
                </td>
                <td  width="20%">

                    <asp:Button id="btnAgregar" runat="server" Text="Agregar al carro" Visible="false" OnClick="btnAgregar_Click"/>
                 
                </td>
                   <td  width="20%">

                     <asp:Button ID="btnVerCompra" runat="server" Text="Ver carro compra" OnClick="btnVerCompra_Click"  Visible="false"/>
                 
                </td>

            </tr>
        </table>
        <table>
            <tr>
                <td align="center">
                    <asp:GridView ID="GridView1" runat="server" ></asp:GridView>
               </td>
            </tr>
        </table>
    </div>
</asp:Content>


  •  Código de la página pedidos.aspx.cs:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace GestionVarios
{
    public partial class Pedidos : System.Web.UI.Page
    {
        private ArrayList productosSeleccionados = new ArrayList();
             
      
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                InicializarDatos();
          

            }
        }

        private void InicializarDatos()
        {

            SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmpresaConnectionString"].ConnectionString);
            try
            {
                Con.Open();
                SqlCommand Com = Con.CreateCommand();
                Com.CommandText = "DameHijosArbolPorProducto";
                Com.CommandType = CommandType.StoredProcedure;
                SqlDataReader Rst = Com.ExecuteReader();

                int i = 0;
                while (Rst.Read())
                {
                    treeViewProductos.Nodes.Add(new TreeNode());
                    treeViewProductos.Nodes[i].Text = Rst["Nombre"].ToString();
                    treeViewProductos.Nodes[i].Value = Rst["IdProducto"].ToString();
                    cargarHijos(Rst["IdProducto"].ToString(),i);
                    i++;
                }
                Rst.Close();
                //Expande todos los nodos
                treeViewProductos.CollapseAll();//.ExpandAll();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                if (Con.State == ConnectionState.Open)
                    Con.Close();
                Con.Dispose();
            }

        }

        private void cargarHijos(string idProducto,int posicionNodo)
        {

            SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmpresaConnectionString"].ConnectionString);
            string IdPadre = String.Empty;
            IdPadre = idProducto;
            try
            {
                Con.Open();
                SqlCommand Com = Con.CreateCommand();
                Com.CommandText = "DameHijosArbolPorProducto";
                Com.CommandType = CommandType.StoredProcedure;
                Com.Parameters.Add("@idProducto", SqlDbType.Int).Value = idProducto;
                SqlDataReader Rst = Com.ExecuteReader();
            

                while (Rst.Read())
                {
                    TreeNode Tn = new TreeNode();
                    Tn.Text = Rst["Nombre"].ToString();
                    Tn.Value = Rst["IdProducto"].ToString();


                    if (Rst["IdPadre"].ToString() != IdPadre)
                    {
                        TreeNode Padre = DameNodoPorId(treeViewProductos.Nodes[posicionNodo], Rst["IdPadre"].ToString());
                        Padre.ChildNodes.Add(Tn);
                    }
                    else
                    {
                        treeViewProductos.Nodes[posicionNodo].ChildNodes.Add(Tn);
                    }
                }

                Rst.Close();
                Com.Dispose();


            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                if (Con.State == ConnectionState.Open)
                    Con.Close();
                Con.Dispose();
            }
        }

        private TreeNode DameNodoPorId(TreeNode Nodo, string Id)
        {
            if (Nodo.Value == Id)
                return Nodo;

            for (int i = 0; i < Nodo.ChildNodes.Count; i++)
            {
                if (Nodo.ChildNodes[i].Value == Id)
                    return Nodo.ChildNodes[i];

                TreeNode RetNodo = DameNodoPorId(Nodo.ChildNodes[i], Id);

                if (RetNodo != null)
                    return RetNodo;
            }
            return null;
        }

        protected void treeViewProductos_SelectedNodeChanged(object sender, EventArgs e)
        {
            TreeNode nodo = treeViewProductos.SelectedNode;
            CargarDatosProducto(nodo.Value);
            btnAgregar.Visible = true;
            txtUnidades.Visible = true;
            lblCantidad.Visible = true;
        }

        private void CargarDatosProducto(string idProducto)
        {
            SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmpresaConnectionString"].ConnectionString);

            try
            {
                Con.Open();
                SqlCommand Com = Con.CreateCommand();
                Com.CommandText = "DameDatosProducto";
                Com.CommandType = CommandType.StoredProcedure;
                Com.Parameters.Add("@idProducto", SqlDbType.Int).Value = idProducto;
                SqlDataReader Rst = Com.ExecuteReader();


                while (Rst.Read())
                {
                    lblDescripcion.Text = "Detalles producto" + Rst["Descripcion"].ToString();
                    lblNombreProducto.Text = "Producto: " + Rst["Nombre"].ToString();
                    lblPrecioDeCompra.Text = "Precio por unidad:" + Rst["PrecioVenta"].ToString() + " € ";
                }

                Rst.Close();
                Com.Dispose();


            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                if (Con.State == ConnectionState.Open)
                    Con.Close();
                Con.Dispose();
            }
        }

        protected void btnAgregar_Click(object sender, EventArgs e)
        {

            btnVerCompra.Visible = true;
            TreeNode nodo = treeViewProductos.SelectedNode;
            productosSeleccionados.Add(nodo.Value);
            productosSeleccionados.Add(txtUnidades.Text);
        
        }


        protected override void LoadViewState(object savedState)
        {
           base.LoadViewState(savedState);
           this.productosSeleccionados = (ArrayList)this.ViewState["productosCarro"];
        }


        protected override object SaveViewState()
        {
            this.ViewState.Add("productosCarro", productosSeleccionados);

            return base.SaveViewState();

        }

        protected void btnVerCompra_Click(object sender, EventArgs e)
        {
           ArrayList productos = this.productosSeleccionados;
          
           DataTable dt = new DataTable();
           dt.Columns.Add("idProducto");
           dt.Columns.Add("Cantidad");

            for (int i = 0; i < productos.Count; i=i+2)
              dt.Rows.Add(productos[i], productos[i + 1]);
           

            CargarListaProducto(dt);

        }

        private void CargarListaProducto(DataTable productos)
        {
            SqlConnection Con = new SqlConnection(ConfigurationManager.ConnectionStrings["EmpresaConnectionString"].ConnectionString);

            try
            {
                Con.Open();
                SqlCommand Com = Con.CreateCommand();
                Com.CommandText = "DameDatosProductos";
                Com.CommandType = CommandType.StoredProcedure;
                Com.Parameters.Add("@Lista", SqlDbType.Structured).Value = productos;
                SqlDataReader Rst = Com.ExecuteReader(CommandBehavior.CloseConnection);

                GridView1.DataSource = Rst;
                GridView1.DataBind();
            

            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
            finally
            {
                if (Con.State == ConnectionState.Open)
                    Con.Close();
                Con.Dispose();
            }
        }
    }
}

No hay comentarios:

Publicar un comentario

Curso .NET Core en C# - 34.Creamos nuestro propio log

34.Creamos nuestro propio log Hola a todos. En este curso, analizaremos todos los conceptos básicos, intermedios y avanzados de  ASP.NET...