Category Archives: RequiredFieldValidator

[RESOLVED] <button disable="disable" does not work if I want to disable behind

I have the following: I would like to disable protected void btnSend_Click(object sender, EventArgs e) { if (Page.IsValid) { btnSend.Disabled = true; System.Threading.Thread.Sleep(2000); } this does not wor

I have the following:
<button id="btnSend" runat="server" alt="" CausesValidation="false" önserverclick="btnSend_Click">
<img id="imgSend" alt="" runat="server" src="~/Images/Buttons/send_ico.gif"
align="top" />


 Send Message</button>


I would like to disable


protected void btnSend_Click(object sender, EventArgs e)
{


if (Page.IsValid)
{
btnSend.Disabled = true;
System.Threading.Thread.Sleep(2000);
}
this does not work.


k.

Can you explain what you are tyring to do? Disabling button when page is valid to stop duplicate postbacks. If so, you can do this...

Markup:

<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" CodeBehind="WebForm5.aspx.cs"
    Inherits="WebApplication1.WebForm5" %>

<!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></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="txt" runat="server"></asp:TextBox>
    <asp:RequiredFieldValidator ErrorMessage="Required" ControlToValidate="txt" ForeColor="Red"
        Display="Dynamic" SetFocusOnError="true" runat="server" />
    <asp:Button ID="buttonSave" runat="server" CausesValidation="true" Text="Do Something"
        OnClick="buttonSave_Click" />
    </form>
</body>
</html>

CodeBehind:

protected void Page_Load(object sender, EventArgs e)
{
    buttonSave.Attributes.Add("onclick""Page_ClientValidate();if(Page_IsValid){this.disabled=true;" +
                                Page.ClientScript.GetPostBackEventReference(buttonSave, "Test") + ";}");

}
protected void buttonSave_Click(object sender, EventArgs e)
{
    Thread.Sleep(2000);
}

Try that way and see if it works. Button will be disabled when page is valid.

sometimes the user can click the button twice.

I want to disable this.

 

buttonSave.Attributes.Add("onclick""Page_ClientValidate();if(Page_IsValid){this.disabled=true;" +
                                Page.ClientScript.GetPostBackEventReference(buttonSave, "Test") + ";}");

this is only good for the asp.net button asp:button tag.

 

<button id="btnSend" runat="server" alt="" CausesValidation="true" onserverclick="btnSend_Click">
                        <img id="imgSend" alt="" runat="server" src="~/Images/Buttons/send_ico.gif"
                            align="top" />
                        <span> <b class="va">Send Message</b></span></button>


this is a html button.

it does not work like a asp:button.

Hi,

Accroding to your code, it seems that the button will be disabled after 2 seconds. Is it what you want to implement?

If I'm not misundertood you, you can try to comment the code "System.Threading.Thread.Sleep(2000)".

Or use the client side javascript:

btnSend.Attributes["onclick"] = "this.disabled = true;";

Here System.Threading.Thread.Sleep(2000) is used to do a delay time manually in order to let us see how this disable property affect the button before the button sumbit.

Above poster give you a good example, whatever the button is asp:button or HtmlButton. It should always work.

I modify it for HtmlButton:

protected void Page_Load(object sender, EventArgs e)
        {
           btnSend.Attributes["onclick"] = "this.disabled = true;";
         }






        protected void btnSend_Click(object sender, EventArgs e)
        {
            System.Threading.Thread.Sleep(2000);
        }


 <asp:ScriptManager ID="ScriptManager1" runat="server">
            </asp:ScriptManager>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                <ContentTemplate>
                    <button id="btnSend" runat="server" alt="send" causesvalidation="false"  onserverclick="btnSend_Click">
                        <img id="img1" alt="" runat="server" src="~/Images/20100920105445544.jpg" align="top" />
                        Send Message</button>
                </ContentTemplate>
            </asp:UpdatePanel>


The button will disabled 2 seconds.

Hope this can help you.

[RESOLVED] changing backcolor of textbox when input is invalid......

Hello I have an ASP.net page with two textboxes where the user types in input.  I applied a requiredfieldvalidator to both textboxes as well.  However, I also want the textboxes to change to a backcolor of red if the form is invalid when the user clicks the button to submit the input.  I tried this code below in tthe button click event, but doesnt work...


If Page.IsValid = False Then
            txtCosts.BackColor = Drawing.Color.Red
            txtRevenue.BackColor = Drawing.Color.Red
        End If

How else can I change the Backcolor of the textboxes when the input is invalid.......

hi bababooey check this link here i explain clearly how to change the textbox background colorwhenever validation fails using asp.net

http://aspdotnet-suresh.blogspot.com/2011/01/how-to-change-textbox-background-color.html

You can do such validations client side.

Ofcourse the page needs to validated on the server too.

Here's an example  

//aspx
<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    <script language="javascript" type="text/javascript">
        function abc(){
            if (typeof (Page_ClientValidate) == 'function') {
            Page_ClientValidate();
            }
            ChangeBackColor();
            if (!Page_IsValid) {
                return false;
            }
            return true;
        }


        function ChangeBackColor() {
            for (var i = 0; i < Page_Validators.length; i++) {
            var val = Page_Validators[i];
            var ctrl = document.getElementById(val.controltovalidate);
            if (ctrl != null && ctrl.style != null) {
                if (!CheckIfValid(ctrl)) {
                    ctrl.style.background = 'red';
            }
            else {
                ctrl.style.background = '';
            }
            ValidatorUpdateIsValid();
            ValidationSummaryOnSubmit(val.validationGroup);
        }


        function CheckIfValid(control) {
            for (var i = 0; i < control.Validators.length; i++) {
                if (!control.Validators[i].isvalid) {
                    return false;
                }
            }
            return true;
        }
    }
}
    </script>
    <div>
      <asp:TextBox ID="TextBox1" runat="server"  ></asp:TextBox>
      <asp:RequiredFieldValidator ID="Req1" runat="server" ErrorMessage="Required" Display="Dynamic"  ControlToValidate="TextBox1" ForeColor="Red"  Text="text1 Required" ValidationGroup="VGrp1"></asp:RequiredFieldValidator>
      <br />
      <asp:Button ID="btnsubmit"  runat="server" Text="Submit" OnClientClick="abc();"  onclick="btnsubmit_Click"/>
    </div>
    </form>


//codebehind
protected void btnsubmit_Click(object sender, EventArgs e)
    {
        Page.Validate("VGrp1");
        if (!Page.IsValid)
        {
            return;
        }
    }


 

If you are interested learning more on client side validation

http://simpledotnetsolutions.wordpress.com/2011/02/06/the-nuts-bolts-of-client-side-validation/

[RESOLVED] FileUpload control don't work on first submission

Hi,

I'm having a problem with the FileUpload control in ASP.NET. It requires two postbacks to server in order to upload the file. In other words, after I select the file and click upload the page reloads but do nothing. Then I reselect the file and click upload then it works.

In my code I put a check for FileUpload.HasFile and it always fails (return false) on the first postback. 

Does anybody have any information regarding this problem?

Thanks.

Q

Are you using fileupload inside update panel. Please post relevant code here

Nikhil,

Yes I did, here's the code.

<asp:UpdatePanel ID="upDefault" runat="server" UpdateMode="Conditional">
                <Triggers>
                    <asp:PostBackTrigger ControlID="UploadButton" />
                </Triggers>
                <ContentTemplate>
                        <asp:FileUpload ID="HinhFU" runat="server" CssClass="largectl" ValidationGroup="UpByFile" />
                        <asp:RequiredFieldValidator ID="rfvFU" runat="server" ErrorMessage="*" ValidationGroup="UpByFile" ControlToValidate="HinhFU" >
                        </asp:RequiredFieldValidator>
                        <asp:Button runat="server" ID="UploadButton" Text="Upload" ValidationGroup="UpByFile" />


                    <asp:Image runat="server" ID="HinhSVImg" Width="100" Height="150" ImageUrl="" Visible="false" />


                </ContentTemplate>
            </asp:UpdatePanel>

In the uploadbutton click I just check for HinhSV.HasFile, if yes then upload it with HinhSV.SaveAs().

Thanks.

Q

fly2thesky

In the uploadbutton click I just check for HinhSV.HasFile
 

I am not sure whether its your mistake while posting! But as per your code there is a fileupload control with id HinhFU and not HinhSV.Innocent

RequiredFieldValidator

Hi guys, I have 2 buttons (submit,cancel) in my webform and 1 requiredfeildvalidator.

When i clickcancel, the requiredfieldvalidator activated, how do I deactivate it?????

Set the CauseValidation property of the Cancel button to false.

Update your Cancel button as follows:

<asp:Button id="Cancel" text="Cancel" CausesValidation="False" runat="server" />

Set the Cause Validation Property of cancel button to False ....Cool

User Control... one strange problem…

Hi,

One strange problem…

I’ve developed one user control for all countries list. Here is the code…

CountryControlBase.vb in App_Code folder
---------------------------------------
Imports Microsoft.VisualBasic
Namespace BlueSky.UserControls
    Public Class CountryControlBase
        Inherits UserControl
        Public Sub New()
            MyBase.New()
        End Sub
        Public Overridable Property Text() As String
            Get
                Return "selected value"
            End Get
            Set(ByVal value As String)
                'child class will override this implementation...
            End Set
        End Property
    End Class
End Namespace
----------------------------------------

--------------------------
CountryControl.ascx
---------------------
<%@ Control Language="VB" AutoEventWireup="false" CodeFile="CountryControl.ascx.vb" Inherits="CountryControl" %>

<asp:DropDownList ID=ddlCountries Runat=server
EnableViewState=True></asp:DropDownList>

<asp:RequiredFieldValidator ID="ddlCountriesRequiredFieldValidator" ControlToValidate="ddlCountries" runat="server" ErrorMessage="RequiredFieldValidator">*</asp:RequiredFieldValidator>
---------------------------------------------------

---------------------------------------------------
CountryControl.ascx.vb
-----------------------------------------------
Imports System.Xml
Imports System.Data
Partial Class CountryControl
    Inherits BlueSky.UserControls.CountryControlBase

    Public Sub New()
        MyBase.new()
    End Sub

    Protected _validate As Boolean

    Public Property Validate() As Boolean
        Get
            Return _validate
        End Get
        Set(ByVal value As Boolean)
            _validate = value
        End Set
    End Property

    Public Overrides Property Text() As String
        Get
            Return ddlCountries.SelectedValue
        End Get
        Set(ByVal Value As String)
            ddlCountries.SelectedValue = Value
        End Set
    End Property

    Private Function UCFirst(ByVal str As String) As String
        str = str.ToLower
        Dim chrFirst As Char
        chrFirst = CType(str.Substring(0, 1), Char)
        chrFirst = CType(chrFirst.ToString.ToUpper, Char)
        str = chrFirst & str.Substring(1, str.Length - 1)

        Return str

    End Function

    Private Function ProperCaseFormat(ByVal str As String) As String
        Return StrConv(str, VbStrConv.ProperCase)
    End Function

    Private Sub generateCountries()
        Dim ds As New DataSet
        Dim i As Integer
        Try
            ds.ReadXml(MapPath("countries.xml"))
            ddlCountries.Items.Add("")
            For i = 0 To ds.Tables(0).Rows.Count - 1
                ddlCountries.Items.Add(ProperCaseFormat(CType(ds.Tables(0).Rows(i).Item(0), String).ToLower))
            Next

        Catch ex As Exception
            Response.Write(ex.Message)
        End Try

        ddlCountries.SelectedValue = Text
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        generateCountries()
    End Sub

    Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
        ddlCountriesRequiredFieldValidator.Enabled = _validate
    End Sub

End Class
-----------------------------------------------------------------------------------------------------------

Now I am using this user control in one of my aspx page like this…
The register statement at the top of the page…
-------------------------
Countries.aspx
-------------------------
<%@ Register TagPrefix="uc" TagName="Country" Src="~/UserControls/Country/CountryControl.ascx" %>
----------------------------
and in between like this...
-------------------------
<uc:Country Id="ddlCountries" runat=Server Validate=False></uc:Country>
--------------------------

Now the problem is that, when I am trying to access this control in codefile…
---------------------
Countries.aspx.vb
---------------------
 Dim c As Control
        c = CType(Me.FindControl("ddlCountries"), BlueSky.UserControls.CountryControlBase)
 Dim country as String
 country = c.Text
-------------------------

But mysteriously… the FindControl is not returning a reference to the control added in the web page and I am getting a “Object reference not set to an instance of an object.” Error.

I am using VB.Net as language and .Net Framework 2.0 with Visual Studio 2005 beta 2 releases.


Please help me…

Thanks,
-Lalit

 

 

IS your aspx page inside master page ?if so you need find control inisde master like this.Page.Master.FindControl("ddlCountries");

Also try and find "ddlCountries" in page source for making sure its present somewhere :)