Category Archives: RangeValidator

[RESOLVED] Validate a calculation

Is it possible to use a Validator control that references the result of multiplying one textbox value times another and make sure it does not exceed a smallmoney value?  For example, txtRate.Text X txtUnits.Text cannot calculate to larger than a smallmoney value 214,748.3648 to 214,748.3647

I am thinking it could be done in a custom validator but was hoping I could do it in one of the built in ones.  Thanks.

You might have to do a custom validation or Set a Range Validator maxValue on key press of either of the textBoxes.

 

On the results textbox , please add  a RangeValidator with Min/Max values as you want.

I think try Type="Double" OR Type="Currency" for that range Validator . Either one should work, I beleive.

[RESOLVED] Dynamic Table help

Hey Guys,

Still somewhat new to asp.net. Have a question I was hoping someone could help with. I have the following on my aspx:

    <asp:Table ID="tblAttendance" runat="server" meta:resourcekey="tblAttendanceResource1" />

Here is the code-behind to dynamically build the table: 

 

void createAttendanceTable()
    {
        tblAttendance.Rows.Clear();
        int x=0;
        int y=0;
        ProgramTableAdapters.READREC_CodeTableAdapter adapter = new ProgramTableAdapters.READREC_CodeTableAdapter();
        Program.READREC_CodeDataTable dtCode = new Program.READREC_CodeDataTable();
        dtCode = adapter.GetData();
        foreach (System.Data.DataRow myDataRow in dtCode.Rows)
        {
            TableRow myTableRow = new TableRow();
            for (x = 0; x <= 1; x++)
            {
               
                TableCell myTableCell = new TableCell();
                switch (x)
                {
                    case 0:
                        if (System.Threading.Thread.CurrentThread.CurrentCulture.ToString() == "fr-CA")
                            myTableCell.Text = myDataRow["Name_French"].ToString() + ":";
                        else
                            myTableCell.Text = myDataRow["Name"].ToString() + ":";
                        myTableCell.HorizontalAlign = HorizontalAlign.Right;
                        switch (myDataRow["Type"].ToString())
                        {
                            case "Attendance":
                                myTableCell.Font.Bold = true;
                                break;
                            case "Absence":
                                myTableCell.Font.Bold = true;
                                break;
                        }
                        break;
                    case 1:
                        TextBox myTextBox = new TextBox();
                        myTextBox.MaxLength = 1;
                        myTextBox.Columns = 1;
                        myTextBox.ID = "txt" + Server.HtmlEncode(myDataRow["ID"].ToString());
                        if (myDataRow["ID"].ToString() == "txtM")
                        {
                           myTextBox.TextChanged += new EventHandler(myTextBox_TextChanged);
                        }
                        myTableCell.Controls.Add(myTextBox);

                        Label myLabel = new Label();
                        if (System.Threading.Thread.CurrentThread.CurrentCulture.ToString() == "fr-CA")
                            myLabel.Text = "jour(s)";
                        else
                            myLabel.Text = "day(s)";
                        myTableCell.Controls.Add(myLabel);

                        int days=determineMaxDays();
                        if (days > 0)
                        {
                            RangeValidator myRangeValidator = new RangeValidator();
                            myRangeValidator.ControlToValidate = myTextBox.ID;
                            myRangeValidator.Display = ValidatorDisplay.Dynamic;
                            myRangeValidator.MaximumValue = days.ToString();
                            myRangeValidator.MinimumValue = "0";
                            if (System.Threading.Thread.CurrentThread.CurrentCulture.ToString() == "fr-CA")
                                myRangeValidator.Text = " * doit être entre " + myRangeValidator.MinimumValue + "-" + myRangeValidator.MaximumValue;
                            else
                                myRangeValidator.Text = " * must be between " + myRangeValidator.MinimumValue + "-" + myRangeValidator.MaximumValue;
                            myRangeValidator.Type = ValidationDataType.Integer;
                            myRangeValidator.ID = "rv" + y.ToString();
                            myTableCell.Controls.Add(myRangeValidator);
                            y = y + 1;
                        }
                        break;
                }
                myTableRow.Cells.Add(myTableCell);
                //if (myTextBox.ID = "txtM")
                //{
                //    Response.Write("Pierre was here");
                //   // myTableRow.Cells.Add(myTableCell);
                //}
            }
            tblAttendance.Rows.Add(myTableRow);
            if (myDataRow["ID"].ToString() == "M")
            {
                TableRow myTblRow = new TableRow();
                //myTblRow.a
                myTblRow.ID = "showMonitorDropDown";
                myTblRow.AccessKey = "1";
                myTblRow.Visible = true;
                TableCell myTableCell = new TableCell();
                DropDownList ddl = new DropDownList();
                ddl.ID = "drop";
                ddl.Items.Clear();
                ddl.Items.Add( "Ex Reading Recovery Student");
                ddl.Items.Add("Current Reading Recovery Student");
                ddl.Items[0].Selected = true;

                myTableCell.HorizontalAlign = HorizontalAlign.Right;
                myTableCell.ColumnSpan = 2;
                

                myTableCell.Text = "Pierre";
                myTableCell.Controls.Add(ddl);
                myTblRow.Cells.Add(myTableCell);
                tblAttendance.Rows.Add(myTblRow);
                //Response.Write("Insert Row");
            }
        }
    }
    
    void myTextBox_TextChanged(object sender, EventArgs e)
    {
        //ctl00_cphContent_showMonitorDropDown.Visible = true;
        Response.Write("gotcha");
    }

What I would like to do seems like it should be fairly simple. If the row is outputting the "M" code, create a hidden row, that will be set to "visible" when the M code textbox has a value entered for it. Otherwise, leave it hidden. It works fine if I make it visible, and don't try to hide anything. Any ideas? Thanks in advance!

Pierre

 

Hi,

th3canad1an

If the row is outputting the "M" code, create a hidden row, that will be set to "visible" when the M code textbox has a value entered for it. Otherwise, leave it hidden. It works fine if I make it visible, and don't try to hide anything.

If I'm not misundertood you. I guess the issue you have now is to find the specific TableRow when the TextBox changed event fired, isn't it?

If so, you need use FindControl method to find the TableRow in Table control and then set the visibel property to true.

Like:

void myTextBox_TextChanged(object sender, EventArgs e)
    {
         TableRow row = this.tblAttendance.FindControl("showMonitorDropDown") as TableRow;
            if (row != null)
                row.Visible = true;

         Response.Write("gotcha");
    }

Also set the visible property to false when creating this TableRow.

Hope this can help you.

[RESOLVED] Session Checkbox Problem

Hi all

im pretty new to vb and im trying to post my checkbox answers onto a another page using "Session". The problem is i cant seem to get the answers to add on so it posts all of the answers checked off. currently it just posts one answer no many how many checkboxes are checked.

heres the code for the first page

 

<%@ Page Language="VB"  %>
<!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" >
<script runat="server">

Sub Submit_Click(ByVal s As Object, ByVal e As System.EventArgs) _
    Handles Submit.Click


        Dim total As String = ""
        
        ' Set the session variable for user options description
        If (Not CheckBox1.Checked And Not CheckBox2.Checked And Not CheckBox3.Checked And Not CheckBox4.Checked And Not CheckBox5.Checked And Not CheckBox6.Checked And Not CheckBox7.Checked And Not CheckBox8.Checked) Then
            ' No checkbox is checked
            Session("UserOptions") = "No boxes selected."
        End If
        If (CheckBox1.Checked) Then
            ' Only direct flight checkbox is checked
            Session("UserOptions") = "Label"
                  
        End If
        If (CheckBox2.Checked) Then
            ' Only direct flight checkbox is checked
            Session("UserOptions") = "Textbox"
                     
            
        End If
        If (CheckBox3.Checked) Then
            ' Only direct flight checkbox is checked
            Session("UserOptions") = " Button "
        End If
        If (CheckBox4.Checked) Then
            ' Only direct flight checkbox is checked
            Session("UserOptions") = " RadioButton "
        End If
        If (CheckBox5.Checked) Then
            ' Only direct flight checkbox is checked
            Session("UserOptions") = " CheckBox "
        End If
        If (CheckBox6.Checked) Then
            ' Only direct flight checkbox is checked
            Session("UserOptions") = " GridView "
        End If
        If (CheckBox7.Checked) Then
            ' Only direct flight checkbox is checked
            Session("UserOptions") = " RangeValidator "
        End If
        If (CheckBox8.Checked) Then
            ' Only direct flight checkbox is checked
            Session("UserOptions") = " RequiredfieldValidator "
        End If
        
        

        Response.Redirect("useroptions.aspx")

    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

    End Sub
</script>
<head>
    <title>Setting session variables example </title>
    <link href="myStyle.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="frmPanel" runat="server">
    
        <asp:CheckBox ID="CheckBox1" runat="server" Text="label " />
        <br />
        <br />
        <br />
        <asp:CheckBox ID="CheckBox2" runat="server" Text="textbox" />
        <br />
        <br />
        <br />
        <asp:CheckBox ID="CheckBox3" runat="server" Text="button" />
        <br />
        <br />
        <br />
        <asp:CheckBox ID="CheckBox4" runat="server" Text="radiobutton" />
        <br />
        <br />
        <br />
        <asp:CheckBox ID="CheckBox5" runat="server" Text="checkbox" />
        <br />
        <br />
        <br />
        <asp:CheckBox ID="CheckBox6" runat="server" Text="gridview" />
        <br />
        <br />
        <br />
        <asp:CheckBox ID="CheckBox7" runat="server" Text="range validator" />
        <br />
        <br />
        <br />
        <br />
        <asp:CheckBox ID="CheckBox8" runat="server" Text="required range validator" />
        <br />
        <br />
        
        <asp:Button ID="Submit" runat="server" Text="Submit" />
</form>
</body>
</html>

 

 

and the second where it posts it

 

<%@ Page Language="VB"  %>
<!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" >
<script runat="server">
    Sub Page_Load(ByVal s As Object, ByVal e As System.EventArgs) Handles Me.Load
        
        Answers.Text = "Your option(s): " & _
            Session("UserOptions")
        
    End Sub
    
</script>
<head>
    <title>Retrieving session variables example </title>
    <link href="myStyle.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="frmUserOptions" runat="server">
    <div >
        <asp:Label runat="server" ID="Answers" Text=""></asp:Label>
    </div>
</form>
</body>
</html>

 

 

You are testing each textbox and if it's checked, you are overwriting you session variable.

You probably want one session variable for each checkbox.

        If (CheckBox2.Checked) Then 
           
' Only direct flight checkbox is checked 
           
Session("UserOptions") = "Textbox" 
                      
             
       
End If 
       
If (CheckBox3.Checked) Then 
           
' Only direct flight checkbox is checked 
           
Session("UserOptions") = " Button " 
       
End If 

In the above piece of code if Checkbox2 and Checkbox3 are checked then the control will go inside both the If conditions. Therefore in the second If condition the session value you set earlier will be overwritten

Try this

Create a class named UserOptions

 

Public Class UserOptions
	Public Property Label() As Boolean
		Get
			Return m_Label
		End Get
		Set
			m_Label = Value
		End Set
	End Property
	Private m_Label As Boolean
	Public Property Textbox() As Boolean
		Get
			Return m_Textbox
		End Get
		Set
			m_Textbox = Value
		End Set
	End Property
	Private m_Textbox As Boolean
	Public Property Button() As Boolean
		Get
			Return m_Button
		End Get
		Set
			m_Button = Value
		End Set
	End Property
	Private m_Button As Boolean
	Public Property RadioButton() As Boolean
		Get
			Return m_RadioButton
		End Get
		Set
			m_RadioButton = Value
		End Set
	End Property
	Private m_RadioButton As Boolean
	Public Property CheckBox() As Boolean
		Get
			Return m_CheckBox
		End Get
		Set
			m_CheckBox = Value
		End Set
	End Property
	Private m_CheckBox As Boolean
	Public Property GridView() As Boolean
		Get
			Return m_GridView
		End Get
		Set
			m_GridView = Value
		End Set
	End Property
	Private m_GridView As Boolean
	Public Property RangeValidator() As Boolean
		Get
			Return m_RangeValidator
		End Get
		Set
			m_RangeValidator = Value
		End Set
	End Property
	Private m_RangeValidator As Boolean
	Public Property RequiredfieldValidator() As Boolean
		Get
			Return m_RequiredfieldValidator
		End Get
		Set
			m_RequiredfieldValidator = Value
		End Set
	End Property
	Private m_RequiredfieldValidator As Boolean
End Class

Set values to this class based on the checkboxes selected and put it in the session.

is there any other way without using classes? i thought you could use the field i set at the top called "total"

and add them using that

One more option would be instead of Response.Redirect(), if you do Server.Transfer().....you can use PReviousPage proerty, by which you can get the controls from the previous page and can get to know which one is checked or selected....

for more info....

http://www.intstrings.com/ramivemula/articles/data-transfer-between-two-asp-net-pages/

Thanks.

Elim

is there any other way without using classes? i thought you could use the field i set at the top called "total"

Is there any reason for not using a class? The solution I suggested is clean. Set the bool properties to true or false based on the user selectection and get the values in the next page.

Elim

is there any other way without using classes?
Like I said, set up one session variable for each CheckBox:

Session("UserOption1") = CStr(CheckBox1.Checked)
Session("UserOption2") = CStr(CheckBox2.Checked)
Session("UserOption3") = CStr(CheckBox3.Checked)
Session("UserOption4") = CStr(CheckBox4.Checked)
Session("UserOption5") = CStr(CheckBox5.Checked)
Session("UserOption6") = CStr(CheckBox6.Checked)
Session("UserOption7") = CStr(CheckBox7.Checked)
Session("UserOption8") = CStr(CheckBox8.Checked)

Then, in your second page:

Dim Option1 as Boolean = CBool(Session("UserOption1"))
Dim Option2 As Boolean = CBool(Session("UserOption2"))
Dim Option3 As Boolean = CBool(Session("UserOption3"))
Dim Option4 As Boolean = CBool(Session("UserOption4"))
Dim Option5 As Boolean = CBool(Session("UserOption5"))
Dim Option6 As Boolean = CBool(Session("UserOption6"))
Dim Option7 As Boolean = CBool(Session("UserOption7"))
Dim Option8 As Boolean = CBool(Session("UserOption8"))

Elim

is there any other way without using classes?

I recommend you to learn some basic OOP before coding.

http://www.eggheadcafe.com/articles/pfc/oopbasics.asp

There is no justification for classophobia in OOP. Classes should be used as needed.

yea im with jerryjoseph you don't want to use a bunch of session variables. your app is going to get messy real quick.

check out this link for all the ways to pass variables between pages:

http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx

i recommend using any of the options on that page besides session variabels :)

zhughes

jerryjoseph you don't want to use a bunch of session variables. your app is going to get messy real quick.
My solution stores eight simple booleans in session, while Jerry's solution stores a single, but much more complex, object in session.

"Messy" is in the eye of the beholder -- I'd suggest that my approach carries a significantly lower overhead.

Just curious,

I used Session Variables a lot before and I found out using session variables can degrade the site performance.

I think you should create a class like jerryjoseph's idea.

OOP is all about classes. Declare and use classes if possible!

Thanks

 

yukiever

using session variables can degrade the site performance.
But:

jerryjoseph

Set values to this class based on the checkboxes selected and put it in the session.
 The issue is not "session variables" vs "class".  Both Jerry's suggestion and mine save the data in session.  Creating a class may or may not be a good idea, but not because it reduces the amount of data saved in session.

On the other hand, ramiramilu's suggestion doesn't use session at all. (But I have no idea whether it is more efficient than using session.)

WombatEd

The issue is not "session variables" vs "class".  Both Jerry's suggestion and mine save the data in session.  Creating a class may or may not be a good idea, but not because it reduces the amount of data saved in session.

On the other hand, ramiramilu's suggestion doesn't use session at all. (But I have no idea whether it is more efficient than using session.)

Exactly....

For this kind of requirement we got to explore different ways of accomplishing this....I dont use Session always, unless I want to store more secured and user specific data along the site....

For transferring some info from one page to other, there are many other options, take example of Querystring.....its simple and easy...for non-sensitive data, i think it is the best possible way....even we can use context.Items.Add() for specific request, in that case data will be only persisted for that particular request...like that there are many options....

Bottom line of the story, all the options are very subjective to the usage for the application, strictly speaking more requirement specific....

Thanks.

[RESOLVED] Decimal Validation range

Members,

I have a requirnent to check the text input within range: 0.00 to 100.00

User must put 0.00 (not 0).
User should always use two decimal places.
User can only enter non negative values.

Regards,
Aloha

You can use a Range Validator.

<asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="RangeValidator" MaximumValue="0" MinimumValue="100" Type="Double"></asp:RangeValidator>

Tried range validator but it allows anything between 0 to 100.

I need regExp for my requirment.

Do you want to do the validation in Javascript or in the code behind?

If you want to use the Javascript (Client Side) then i suggest you use something like this...

http://www.pageresource.com/jscript/j_a_03.htm

 

also here is some code that i created by using info from that site...

 

function test()
{
    var a = new Number(document.getElementById('txt').value);
    if (a < 0 ||  a > 100) {
        alert("only values between 0.00 and 100.00 are allowed");
    }
    
     
    else {
        alert(a.toFixed(2).toString());
        return true;
    }
}

 

 

and to understand more about the number class here is also a reference to that...

http://rx4ajax-jscore.com/ecmacore/object/number.html

 

Good luck.

Ok, try this regex:

(^100([.]0{1,2})?)$|(^\d{1,2}([.]\d{1,2})?)$

Hi,

Please check the link below for the sample:

http://www.asp.net/AJAX/AjaxControlToolkit/Samples/MaskedEdit/MaskedEdit.aspx

Hope this helps.

Hi,

AlohaMora

I need regExp for my requirment.

According to your description ,I would like to suggest you to use the regular expression like this:

(100|[0-9]?\d)(\.\d{2}).*?

AlohaMora

I have a requirnent to check the text input within range: 0.00 to 100.00

User must put 0.00 (not 0).
User should always use two decimal places.
User can only enter non negative values.

Please check the complete sample below:

1.Code in page(.aspx):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="GetValue" onclick="Button1_Click" />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" Display="Dynamic" runat="server" ControlToValidate="TextBox1"
            ErrorMessage="Please enter the value in textbox control"></asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator  Display="Dynamic" ID="Regularexpressionvalidator1" runat="server" ControlToValidate="TextBox1"
            ErrorMessage="Error Format" ValidationExpression="(100|[0-9]?\d)(\.\d{2}).*?"></asp:RegularExpressionValidator>
    </div>
    </form>
</body>
</html>

2.Code in page(.cs):

 protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Write("Value : " + this.TextBox1.Text);
    }

Hope it can help you.

If you use RangeValidator for validation - 0, 0.0 and 0.00 should all validate. Cannot understand the reason on why this has to be 0.00...

[RESOLVED] Validation Controls without JS

I wonna ask about validtaion controls in ASP Net.They working on server-side when JS is disabled??????

Yes.

Thx for answer,U may show me any examples, i havent idea whats wrong i did.When i disabled JS validation controls it didnt work on client and server-side.

Commands Page.IsValid,Page.Validate(),didnt work too.

To validate the server validators, call Page.Validate() and then check for Page.IsValid....

Thanks

Its ,not working- Page.IsValid give always result true whene forms is correct or not,i dunno why:(

I found on this forum my answer :http://forums.asp.net/t/944362.aspx.

The Validator is inside another control that is Visible=false not working in serwer-side

 

this is from MSDN Documnetation - 

For this property to return true, all validation server controls in the current validation group must validate successfully. You should check this property only after you have called the Page.Validate method, or set the CausesValidation property to true in the OnServerClick event handler for an ASP.NET server control that initiates form processing. These server controls include the ButtonHtmlButtonHtmlInputButtonHtmlInputImageImageButton, and LinkButton classes.

So please check for ValidationGroup if any and also check for CausesValidation property....

Thanks.

I solved my problem: if (IsPostBack){ panel1.Visible=true; Page.Validate(); if (Page.IsValid) { panel1.Visible=false; Message.Text = "Page is valid."; } else { Message.Text = "Page is not valid!"; } }} Visible panel before page is validate ,where are a input boxes and validation controls,and hide panel whene page.IsValid.Working on server-side now:)