Autor Tema: Condicionar validadores asp.net  (Leído 3170 veces)

reenurya

  • Sin experiencia
  • *
  • APR2.COM
  • Mensajes: 4
    • Ver Perfil
Condicionar validadores asp.net
« en: 30 de Abril 2016, 04:55 »
Cordial saludo.
Cómo puedo hacer para que los validator de esta página sólo se activen cuando deseo insertar un nuevo registro o para validar los datos a actualizar después de hacer clic en el botón?, si no los marco como comentarios apenas cargo los datos me muestra los mensajes del validator. Adjunto código:
Default.aspx.cs:

Código: [Seleccionar]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;

public partial class _Default : System.Web.UI.Page
{
    //cadena de conexion la declaramos a nivel de la clase para utilizarla en todos los eventos.
    SqlConnection cn = new SqlConnection("Data Source=(local)\\sqlexpress;Initial Catalog=clientes;Persist Security Info=True;User ID=sa;Password=admin+123");

    protected void Page_Load(object sender, EventArgs e)
    {
        this.cargardatos();
    }

    public void cargardatos()
    {
        //hacemos la consulta a la base de datos
        SqlCommand cmd = new SqlCommand("Select * from cliente", cn);

        //objeto adapter para hacer el enlace y llenado del dataset
        SqlDataAdapter adapter = new SqlDataAdapter();

        //asignamos la propiedad selectcommand al objeto command para que ejecute consulta
        adapter.SelectCommand = cmd;

        //abrimos la conexion
        cn.Open();

        //creamos objeto dataset
        DataSet objdataset = new DataSet();

        //llenamos el datable del dataset
        //el metodo fill obtiene los datos recuperados del dataadapter y los coloca dentro del dataset
        adapter.Fill(objdataset);

        //cerramos conexion
        cn.Close();

        //enlazamos los datos al griedvied
        GridView1.DataSource = objdataset;
        GridView1.DataBind();
    }


    protected void btnBuscar_Click(object sender, EventArgs e)
    {
        SqlCommand cmd_sel = new SqlCommand("select_cliente_ok", cn);
        cmd_sel.CommandType = CommandType.StoredProcedure;

        cmd_sel.Parameters.Add("@at_id_cliente", SqlDbType.Decimal);

        cmd_sel.Parameters.Add("@msj", SqlDbType.VarChar, 50);
        cmd_sel.Parameters["@msj"].Direction = ParameterDirection.Output;

        cmd_sel.Parameters["@at_id_cliente"].Value = Convert.ToDecimal(txtBusCC.Text);
        //cmd_sel.Parameters["@msj"].Value = null;

        cn.Open();
        cmd_sel.ExecuteNonQuery();
        SqlDataReader reader = cmd_sel.ExecuteReader();
       

        if (reader.Read())
        {
            txtId.Text = Convert.ToString(cmd_sel.Parameters["@at_id_cliente"].Value);
            txtNom.Text = reader.GetString(0);
            txtDir.Text = reader.GetString(1);
            txtTel.Text = reader.GetString(2);
            lblEstado.Text = Convert.ToString(cmd_sel.Parameters["@msj"].Value);
            reader.Close();
        }
        else
        {
            lblEstado.Text = Convert.ToString(cmd_sel.Parameters["@msj"].Value);
        }

        this.cargardatos();
    }
   
   

    protected void btnActualizar_Click(object sender, EventArgs e)
    {
        SqlCommand cmd_sel = new SqlCommand("actualiza_cliente3", cn);
        cmd_sel.CommandType = CommandType.StoredProcedure;

        cmd_sel.Parameters.Add("@at_id_cliente", SqlDbType.Decimal);
        cmd_sel.Parameters.Add("@at_mod_id_cliente", SqlDbType.Decimal);
        cmd_sel.Parameters.Add("@at_nom", SqlDbType.VarChar);
        cmd_sel.Parameters.Add("@at_dir", SqlDbType.VarChar);
        cmd_sel.Parameters.Add("@at_tel", SqlDbType.VarChar);

        cmd_sel.Parameters.Add("@msj", SqlDbType.VarChar, 50);
        cmd_sel.Parameters["@msj"].Direction = ParameterDirection.Output;

        cmd_sel.Parameters["@at_id_cliente"].Value = Convert.ToDecimal(txtBusCC.Text);
        cmd_sel.Parameters["@at_mod_id_cliente"].Value = Convert.ToString(txtId.Text);
        cmd_sel.Parameters["@at_nom"].Value = Convert.ToString(txtNom.Text);
        cmd_sel.Parameters["@at_dir"].Value = Convert.ToString(txtDir.Text);
        cmd_sel.Parameters["@at_tel"].Value = Convert.ToString(txtTel.Text);
        cmd_sel.Parameters["@msj"].Value = null;


        cn.Open();
        cmd_sel.ExecuteNonQuery();
        SqlDataReader reader = cmd_sel.ExecuteReader();

        lblEstado.Text = Convert.ToString(cmd_sel.Parameters["@msj"].Value);

        this.cargardatos();

    }
}
Default.aspx
Código: [Seleccionar]
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <style type="text/css">
        .auto-style1 {
            width: 78%;
        }
        .auto-style2 {
            width: 346px;
        }
        .auto-style3 {
            width: 366px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
         <h4>Insertar datos con procedimiento almacenado:</h4> 
        <br />
        <asp:GridView ID="GridView1" runat="server"></asp:GridView>
         <br />
         <table class="auto-style1">
             <tr>
                 <td class="auto-style2">
                     <asp:Label ID="Label5" runat="server" Text="Ingrese el número de cédula a buscar"></asp:Label>
                 </td>
                 <td class="auto-style3">
                     <asp:TextBox ID="txtBusCC" runat="server"></asp:TextBox>
                 </td>
             </tr>
             <tr>
                 <td class="auto-style2">
                     <asp:Label ID="Label1" runat="server" Text="Cédula:"></asp:Label>
                 </td>
                 <td class="auto-style3">
                     <asp:TextBox ID="txtId" runat="server"></asp:TextBox>
                     <%--<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtId" ErrorMessage="Campo requerido" Display="Dynamic"></asp:RequiredFieldValidator>
                     <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txtId" ValidationExpression="^\d+$" ErrorMessage="Por favor ingrese sólo números." Display="Dynamic"></asp:RegularExpressionValidator>--%>
                 </td>
             </tr>
             <tr>
                 <td class="auto-style2">
                     <asp:Label ID="Label2" runat="server" Text="Nombre:"></asp:Label>
                 </td>
                 <td class="auto-style3">
                     <asp:TextBox ID="txtNom" runat="server"></asp:TextBox>
                     <%--<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtNom" ErrorMessage="Campo requerido" Display="Dynamic"></asp:RequiredFieldValidator>
                     <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txtNom" ValidationExpression="^[A-Z0-9 a-z]*$" ErrorMessage="Por favor ingrese sólo letras y espacios en blanco." Display="Dynamic"></asp:RegularExpressionValidator>--%>
                 </td>
             </tr>
             <tr>
                 <td class="auto-style2">
                     <asp:Label ID="Label3" runat="server" Text="Dirección:"></asp:Label>
                 </td>
                 <td class="auto-style3">
                     <asp:TextBox ID="txtDir" runat="server"></asp:TextBox>
                     <%--<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtDir" ErrorMessage="Campo requerido" Display="Dynamic"></asp:RequiredFieldValidator>--%>
                 </td>
             </tr>
             <tr>
                 <td class="auto-style2">
                     <asp:Label ID="Label4" runat="server" Text="Teléfono:"></asp:Label>
                     
                 </td>
                 <td class="auto-style3">
                     <asp:TextBox ID="txtTel" runat="server"></asp:TextBox>
                     <%--<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txtTel" ErrorMessage="Campo requerido" Display="Dynamic"></asp:RequiredFieldValidator>
                     <asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" ControlToValidate="txtTel" ValidationExpression="^\+?\d{1,3}?[- .]?\(?(?:\d{2,3})\)?[- .]?\d\d\d[- .]?\d\d\d\d$" ErrorMessage="Por favor ingrese un número telefónico válido." Display="Dynamic"></asp:RegularExpressionValidator>--%>
                 </td>
             </tr>
             <tr>
                 <td class="auto-style2">
                     <asp:Button ID="btnBuscar" runat="server" OnClick="btnBuscar_Click" Text="Buscar" Width="87px" />
                 </td>
                 <td class="auto-style3">
                     <asp:Label ID="lblEstado" runat="server"></asp:Label>
                 </td>
             </tr>
             <tr>
                 <td class="auto-style2">
                     <asp:Button ID="btnActualizar" runat="server" OnClick="btnActualizar_Click" Text="Actualizar" />
                 </td>
                 <td class="auto-style3">
                     &nbsp;</td>
             </tr>
             <tr>
                 <td class="auto-style2">
                     &nbsp;</td>
                 <td class="auto-style3">
                     &nbsp;</td>
             </tr>
             <tr>
                 <td class="auto-style2">
                     &nbsp;</td>
                 <td class="auto-style3">
                     &nbsp;</td>
             </tr>
         </table>
         <br />
        <br />
   
    </div>
    </form>
</body>
</html>


César Krall

  • Moderador Global
  • Experto
  • *******
  • Mensajes: 2078
  • No vales por lo que dices, sino por lo que haces
    • Ver Perfil
    • aprenderaprogramar.com
Re:Condicionar validadores asp.net
« Respuesta #1 en: 01 de Mayo 2016, 18:25 »
Hola!

Si usas elementos de validación en tiempo real, se mostrarán los mensajes de validación antes de enviar el formulario. Si no quieres que se muestren los mensajes establece la propiedad Display del control RequiredFieldValidator según prefieras: static hace que se muestre el mensaje sobre la página reservando un espacio específico, dynamic hace que se muestre el mensaje creando un espacio dinámicamente, none hace que el mensaje de validación no se muestre.

Ejemplo

Código: [Seleccionar]
<form id="form1" runat="server">

   <table style="width: 66%;">
   
      <tr>
         <td class="style1" colspan="3" align="center">
         <asp:Label ID="lblmsg"
            Text="President Election Form : Choose your president"
            runat="server" />
         </td>
      </tr>

      <tr>
         <td class="style3">
            Candidate:
         </td>

         <td class="style2">
            <asp:DropDownList ID="ddlcandidate" runat="server"  style="width:239px">
               <asp:ListItem>Please Choose a Candidate</asp:ListItem>
               <asp:ListItem>M H Kabir</asp:ListItem>
               <asp:ListItem>Steve Taylor</asp:ListItem>
               <asp:ListItem>John Abraham</asp:ListItem>
               <asp:ListItem>Venus Williams</asp:ListItem>
            </asp:DropDownList>
         </td>

         <td>
            <asp:RequiredFieldValidator ID="rfvcandidate"
               runat="server" ControlToValidate ="ddlcandidate"
               ErrorMessage="Please choose a candidate"
               InitialValue="Please choose a candidate">
            </asp:RequiredFieldValidator>
         </td>
      </tr>

      <tr>
         <td class="style3">
            House:
         </td>

         <td class="style2">
            <asp:RadioButtonList ID="rblhouse" runat="server" RepeatLayout="Flow">
               <asp:ListItem>Red</asp:ListItem>
               <asp:ListItem>Blue</asp:ListItem>
               <asp:ListItem>Yellow</asp:ListItem>
               <asp:ListItem>Green</asp:ListItem>
            </asp:RadioButtonList>
         </td>

         <td>
            <asp:RequiredFieldValidator ID="rfvhouse" runat="server"
               ControlToValidate="rblhouse" ErrorMessage="Enter your house name" >
            </asp:RequiredFieldValidator>
            <br />
         </td>
      </tr>

      <tr>
         <td class="style3">
            Class:
         </td>

         <td class="style2">
            <asp:TextBox ID="txtclass" runat="server"></asp:TextBox>
         </td>

         <td>
            <asp:RangeValidator ID="rvclass"
               runat="server" ControlToValidate="txtclass"
               ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
               MinimumValue="6" Type="Integer">
            </asp:RangeValidator>
         </td>
      </tr>

      <tr>
         <td class="style3">
            Email:
         </td>

         <td class="style2">
            <asp:TextBox ID="txtemail" runat="server" style="width:250px">
            </asp:TextBox>
         </td>

         <td>
            <asp:RegularExpressionValidator ID="remail" runat="server"
               ControlToValidate="txtemail" ErrorMessage="Enter your email"
               ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
            </asp:RegularExpressionValidator>
         </td>
      </tr>

      <tr>
         <td class="style3" align="center" colspan="3">
            <asp:Button ID="btnsubmit" runat="server" onclick="btnsubmit_Click"
               style="text-align: center" Text="Submit" style="width:140px" />
         </td>
      </tr>
   </table>
   <asp:ValidationSummary ID="ValidationSummary1" runat="server"
      DisplayMode ="BulletList" ShowSummary ="true" HeaderText="Errors:" />
</form>

Tras hacer click en el botón de envío de formulario se mostrará el resultado:

Código: [Seleccionar]
protected void btnsubmit_Click(object sender, EventArgs e)
{
   if (Page.IsValid)
   {
      lblmsg.Text = "Thank You";
   }
   else
   {
      lblmsg.Text = "Fill up all the fields";
   }
}

Saludos!
Responsable de departamento de producción aprenderaprogramar.com

 

Sobre la educación, sólo puedo decir que es el tema más importante en el que nosotros, como pueblo, debemos involucrarnos.

Abraham Lincoln (1808-1865) Presidente estadounidense.

aprenderaprogramar.com: Desde 2006 comprometidos con la didáctica y divulgación de la programación

Preguntas y respuestas

¿Cómo establecer o cambiar la imagen asociada (avatar) de usuario?
  1. Inicia sesión con tu nombre de usuario y contraseña.
  2. Pulsa en perfil --> perfil del foro
  3. Elige la imagen personalizada que quieras usar. Puedes escogerla de una galería de imágenes o subirla desde tu ordenador.
  4. En la parte final de la página pulsa el botón "cambiar perfil".