Insert values from C # text boxes in (ASP.NET) to SQL Server

0

Good I am new in the subject for development, work in a project, the code was provided to me, my case is that I have to capture values of 3 text boxes and store them in a database in SQL Server, mainly they are 3 values to store as E-Mail type and save them in their respective columns [ EmailNotificaError , EmailNotificaInicio , EmailNotificaFin ] in a table called TInterfaces using a stored procedure to insert

I am still investigating, thank you in advance.

Data: interface [DetailNotifies.aspx]

      <div class="form-row">
            <!-- Input NotificarErrorMail -->
        <div class="form-group col-md-3">
            <div class="form-group form-check">
                <input type="checkbox" class="form-check-input" id="Marcar1" value="1" onchange="javascript:MuestraBoton1()">
                <label class="form-check-label" for="exampleCheck1">Notificar solamente al ocurrir un error E-Mail</label>
                <asp:textbox id="Contenido1" runat="server" cssclass="form-control" placeholder="Ingresa E-Mail"></asp:textbox>
            </div>
        </div>
            <!-- Input NotificarEjecMail -->
        <div class="form-group col-md-3">
            <div class="form-group form-check">
                <input type="checkbox" class="form-check-input" id="Marcar2" value="1" onchange="javascript:MuestraBoton2()">
                <label class="form-check-label" for="exampleCheck1">Notificar al inicio de e ejecución E-Mail</label>
                <asp:textbox id="Contenido2" runat="server" cssclass="form-control" placeholder="Ingresa E-Mail"></asp:textbox>
            </div>
        </div> 
            <!-- Input NotificarEjecFin -->
        <div class="form-group col-md-3">
            <div class="form-group form-check">
                <input type="checkbox" class="form-check-input" id="Marcar3" value="1" onchange="javascript:MuestraBoton3()">
                <label class="form-check-label" for="exampleCheck1">Notificar al  final de ejecución E-Mail </label>
                <asp:textbox id="Contenido3" runat="server" cssclass="form-control" placeholder="Ingresa E-Mail" ></asp:textbox>
            </div>
        </div>

            <!-- Input Guardar & Enviar -->
            <div class="form-group col-md-3 items-center">
                <div class="btn-group btn-group-toggle" data-toggle="buttons">
                    <label class="btn btn-secondary btn btn-outline-secondary">
                        <input type="checkbox" name="marcarTodo" id="group1" />
                        Marcar Notificaciones E-Mail
                    </label>
                    <label class="btn btn-secondary btn btn-outline-secondary">
                        <input type="checkbox">
                        Enviar
                    </label>
                </div>
            </div>

        </div>

Code [DetailNotifies.aspx.cs]

using System;
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 InterfacesAGA
{
    public partial class DetalleNotifica : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string sql = string.Empty;
            try{

                SqlConnection cnConexion = new SqlConnection();
                cnConexion.ConnectionString = ConfigurationManager.ConnectionStrings["cnInterfaces"].ToString();
                SqlCommand comando = new SqlCommand();
                SqlDataAdapter adapt = new SqlDataAdapter();
                comando.Connection = cnConexion;
                comando.CommandType = CommandType.StoredProcedure;
                comando.CommandText = sql;
                sql = "spHeaderInterface";

                hidIdInterface.Value = Request.QueryString["id"].ToString();

                SqlParameter pIdInterface = new SqlParameter("IdInterface", SqlDbType.Int);
                pIdInterface.Value = Convert.ToInt32(Request.QueryString["id"]);
                comando.Parameters.Add(pIdInterface);
                if (cnConexion != null && !cnConexion.State.Equals(ConnectionState.Closed))
                    cnConexion.Close();
                else
                    cnConexion.Open();
                SqlDataReader dr = comando.ExecuteReader();
                if (dr.HasRows)
                    if (dr.Read())
                    {
                        hidIdInterface.Value = Request["id"].ToString();
                        lblNombre.Text = (dr.IsDBNull(dr.GetOrdinal("Nombre")) ? "" : dr.GetString(dr.GetOrdinal("Nombre")));
                        lblDescripcion.Text = (dr.IsDBNull(dr.GetOrdinal("Descripcion")) ? "" : dr.GetString(dr.GetOrdinal("Descripcion")));
                        if (dr.IsDBNull(dr.GetOrdinal("Activo")))
                        {
                            imgInterfaceActiva.ImageUrl = "images/inactivo.gif";
                            imgInterfaceActiva.ToolTip = "Interface inactiva";
                        }
                        else
                        {
                            if (dr.GetBoolean(dr.GetOrdinal("Activo")))
                            {
                                imgInterfaceActiva.ImageUrl = "images/activo.gif";
                                imgInterfaceActiva.ToolTip = "Interface activa";
                            }
                            else
                            {
                                imgInterfaceActiva.ImageUrl = "images/inactivo.gif";
                                imgInterfaceActiva.ToolTip = "Interface inactiva";
                            }
                        }

                        if (dr.IsDBNull(dr.GetOrdinal("UltimaEjec")))
                            lblUltimaEjec.Text = "Nunca se ha ejecutado";
                        else
                            lblUltimaEjec.Text = String.Format("{0:dddd, MMMM d, yyyy  HH:mm:ss}", dr.GetDateTime(dr.GetOrdinal("UltimaEjec")));
                        if (dr.IsDBNull(dr.GetOrdinal("SiguienteEjec")))
                            lblProximaEjec.Text = "No está configurada su siguente ejecución";
                        else
                            lblProximaEjec.Text = String.Format("{0:dddd, MMMM d, yyyy  HH:mm:ss}", dr.GetDateTime(dr.GetOrdinal("SiguienteEjec")));                    

                    }

                comando.Dispose();
                cnConexion.Close();
                cnConexion.Dispose();
            }
            catch (Exception ex)
            {
                lblNombre.Text = "¡Ocurrió un error al leer el registro! " + ex.Message;
                lblNombre.Visible = true;
            }
        }

    }
}

Data: Stored procedure to insert

USE [Interfaces]
GO
04/10/2018 12:19:10 p.m. ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[sp_InsertaMailTI]
    @EmailNotificaError varchar(100) = NULL,
    @EmailNotificaInicio varchar (100) = NULL,
    @EmailNotificaFin varchar (100) = NULL
AS
BEGIN
    SET NOCOUNT ON;
    INSERT INTO dbo.TInterfaces(EmailNotificaError,EmailNotificaInicio,EmailNotificaFin) VALUES (@EmailNotificaError,@EmailNotificaInicio,@EmailNotificaFin);
END
    
asked by Igmar Jovan Hernández 04.10.2018 в 19:26
source

1 answer

1

Some comments regarding the code, you could reduce it a lot if you use a using block for the connection object

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
        string connstring = ConfigurationManager.ConnectionStrings["cnInterfaces"].ToString();
        using(SqlConnection cnConexion = new SqlConnection(connstring))
        {
            string sql = "spHeaderInterface";
            SqlCommand comando = new SqlCommand(sql, cnConexion);
            comando.CommandType = CommandType.StoredProcedure;

            hidIdInterface.Value = Request.QueryString["id"].ToString();
            comando.Parameters.AddWithValue("@IdInterface", Convert.ToInt32(Request.QueryString["id"]));

            SqlDataReader dr = comando.ExecuteReader();

            if (dr.Read())
            {
                hidIdInterface.Value = Request["id"].ToString();
                lblNombre.Text = dr["Nombre"] == DBNull.Value ? "" : dr["Nombre"].ToString();
                lblDescripcion.Text = dr["Descripcion"] == DBNull.Value ? "" : dr["Descripcion"].ToString(); 

                //resto codigo
            }
        }

    }
    catch (Exception ex)
    {
        lblNombre.Text = "¡Ocurrió un error al leer el registro! " + ex.Message;
        lblNombre.Visible = true;
    }
}

on the other hand to insert your code block should be something like this

protected void button1_click(object sender, EventArgs e)
{
    try
    {
        string connstring = ConfigurationManager.ConnectionStrings["cnInterfaces"].ToString();
        using(SqlConnection cnConexion = new SqlConnection(connstring))
        {
            string sql = "sp_InsertaMailTI";
            SqlCommand comando = new SqlCommand(sql, cnConexion);
            comando.CommandType = CommandType.StoredProcedure;

            comando.Parameters.AddWithValue("@EmailNotificaError", Contenido1.Text);
            comando.Parameters.AddWithValue("@EmailNotificaInicio", Contenido2.Text);
            comando.Parameters.AddWithValue("@EmailNotificaFin", Contenido3.Text);

            comando.ExecuteNonQuery();

        }

    }
    catch (Exception ex)
    {
        lblNombre.Text = "¡Ocurrió un error al leer el registro! " + ex.Message;
        lblNombre.Visible = true;
    }
}
    
answered by 05.10.2018 / 06:01
source