Enabling/Disabling RegularExpressionValidator in code behind - asp.net

I have a problem with RegularExpressionValidator connected with TextBox:
<asp:TextBox ID="tbPRCOD" runat="server" Font-Bold="True" ForeColor="Green" BackColor="White" BorderStyle="None" Width="50%"></asp:TextBox>
<asp:RegularExpressionValidator id="revPRCOD" runat="server" SetFocusOnError="True"
ErrorMessage="<%$ Resources:GlobalTranslations, max20char %>" Display="Dynamic"
ControlToValidate="tbPRCOD" BackColor="Transparent" Font-Bold="True"
Font-Underline="True" ForeColor="Red" ValidationExpression="^[a-zA-Z0-9]{0,20}$">
On page I have Drop down list:
<asp:DropDownList ID="cmbIDFAM" runat="server" Width="98%" SkinID="mandatoryCombo" Font-Size="X-Small" AutoPostBack="true" > </asp:DropDownList></td>
At start validator is enabled (if string in text box will be over 20 characeters then validator shows validate error). If I change selected item in DropDownList to item with value 5 then I want to turn off validation because for this index in DropDownList, I want to write in TextBox (tbPRCOD) more than 20 characters:
Protected Sub cmbIDFAM_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbIDFAM.SelectedIndexChanged
If getValueFromCombo(cmbIDFAM) = 5 Then
tbPRCOD.MaxLength = 100
revPRCOD.Enabled = False
Else
tbPRCOD.MaxLength = 20
revPRCOD.Enabled = True
End If
End Sub
Everything works fine until I change cmbIDFAM DropDownList to 5th item. I put in TextBox more than 20 characters, and now RegularExpressionValidator is disabled so it don't show error in validate. When I change item in ddl then in TextBox is more than 20 characters and validator is enabled, but error doesn't show in page. Why? How to force validation? I also use function to force Validation, after change item in ddl:
revPRCOD.Validate()
This won't help in this situation. Thanks for Help.
Mat.

Related

Required field validator doesn´t work

I have this code in my ASPX view:
<asp:TextBox ID="txtDate" runat="server" class="form-control" type="text"></asp:TextBox>
<asp:RequiredFieldValidator id="rfvDate" runat="server" ControlToValidate="txtDate" ErrorMessage="Obligatory field" ViewStateMode="Enabled" CssClass="alert-danger"></asp:RequiredFieldValidator>
</div>
the error message appears correctly when I leave the field empty, but I also want to show an error message when the date is not correctly, I do this in my code behind but it doesn´t work:
Private Sub Mybutton_Click(sender As Object, e As EventArgs) Handles Mybutton.Click
If IsDate(txtDate.Text.ToString) = False Then
rfvDate.IsValid = False
rfvDate.Visible = True
rfvDate.ErrorMessage = "Check that it is a valid date"
Exit Sub
Else
'DO THE REST OF THE CODE
End Sub
What am I doing wrong? thanks
you can use both RequiredField Validator along with RegularExpressionValidator
<asp:RegularExpressionValidator runat="server" ControlToValidate="txtDate" ValidationExpression="(((0|1)[1-9]|2[1-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$"
ErrorMessage="Invalid date format." CssClass="alert-danger" ValidationGroup="Group1" />
Add the ValidationGroup="Group1" to the Button aspx markup

How do I access a hyperlink control that's in a gridview from _RowEditing Sub?

I've run into a wall and could use some advice. I have a gridview that contains a "Details" hyperlink on each row. While I am in edit mode (inline), I want to disable the details link. I thought this would be simple, but I can't seem to make it work. I had assumed (wrongly) that I could do something like:
Dim lnkDetails As HyperLink = CType(e.Row.FindControl("lnkDetails"), HyperLink)
lnkDetails.Enabled = False
The problem here, as I found out, is the "e As GridViewEditEventArgs" part of my Sub doesn't include "Row".
Here is the relevant code:
Protected Sub gvCurRecords_RowEditing(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
' Make the GridView control into edit mode for the selected row.
gvCurRecords.EditIndex = e.NewEditIndex
' Rebind the GridView control to show data in edit mode.
BindGridView()
' Hide the Add button.
lbtnAdd.Visible = False
End Sub
HTML (Only the relevant column):
<asp:GridView ID="gvCurRecords" CellPadding="4" DataSourceId="SqlDataSource1"
Autogeneratecolumns="false" AutoGenerateEditButton="true"
AutoGenerateDeleteButton="true" OnRowEditing="gvCurRecords_RowEditing"
OnRowCancelingEdit="gvCurRecords_RowCancelingEdit"
OnRowUpdating="gvCurRecords_RowUpdating" DataKeyNames="eventID"
OnRowDataBound="gvCurRecords_RowDataBound"
OnPageIndexChanging="gvCurRecords_PageIndexChanging" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="lnkDetails" runat="server" Text='Details' NavigateUrl='<%#FormatUrl(CInt(Eval("EventID")))%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:Gridview>
Any help would be greatly appreciated. Thanks.
Use the edit template to define a label instead of a hyperlink:
<EditItemTemplate>
<asp:Label ID="lbDetails" runat="server" Text='something else' />
</EditItemTemplate>

Clear Textbox with Regular Expression Validator

I Got a text box with a Regular Expression validator, to validate if my textbox is numeric.
here's the code :
<asp:TextBox ID="txtAmount" runat="server" CssClass="TextBoxCls"></asp:TextBox>
<asp:RegularExpressionValidator runat="server" ID="valNumbersOnly" ControlToValidate="txtAmount"
SetFocusOnError="true" Display="Dynamic" ErrorMessage="Please enter a numbers only in text box."
Font-Bold="true" ForeColor="Red" ValidationExpression="(^([0-9 ]*|\d*\d{1}?\d*)$)">
</asp:RegularExpressionValidator>
and , if the user accidentally input the wrong data , it'll show the Error Like This :
and i give the user, a clear function to clear all the textbox : with kind of this function :
Public Sub ClearTextBox(ByVal root As Control)
For Each ctrl As Control In root.Controls
ClearTextBox(ctrl)
If TypeOf ctrl Is TextBox Then
CType(ctrl, TextBox).Text = String.Empty
End If
Next ctrl
End Sub
Protected Sub btnClr_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClr.Click
ClearTextBox(Me)
dropResponse.SelectedIndex = 0
FillData()
End Sub
but , the amount is not cleared, it still show the error. why it still happen?
If you are providing this through another button on the same form it won't ever hit the code-behind.
If you want a button on a validated form that needs to fire regardless of whether the other controls have validated, put it in a separate validation group:
<asp:Button runat="server" ID="btnClr" Text="Clear form" OnClick="btnClr_Click" ValidationGroup="unvalidatedControls" />
Alternatively, put a validation group on your controls that need validating and also the button that submits the form:
<asp:TextBox ID="txtAmount" runat="server" CssClass="TextBoxCls" ValidationGroup="validatedControls"></asp:TextBox>
<asp:RegularExpressionValidator runat="server" ID="valNumbersOnly" ControlToValidate="txtAmount"
SetFocusOnError="true" Display="Dynamic" ErrorMessage="Please enter a numbers only in text box."
Font-Bold="true" ForeColor="Red" ValidationExpression="(^([0-9 ]*|\d*\d{1}?\d*)$)"
ValidationGroup="validatedControls">
</asp:RegularExpressionValidator>
<asp:Button runat="server" ID="btnSubmit" Text="Submit Form" ValidationGroup="validatedControls" />
You could put a ValidationGroup attribute on both your clear button and the main form, as long as they're different, the clear button will work just fine.
Some documentation on Validation Groups: http://msdn.microsoft.com/en-us/library/ms227424.aspx
I suspect that the textbox is contained in a panel or another container control. Only the toplevel controls of a page are available in the controls collection of the page.
I would suggest to change the parameter of the call to ClearTextBox with the correct container control.

asp.net VB gridview checkbox always show false on serverside code behind

I am trying to implement a gridview with checkbox column on asp.net (VB). when the user checks checkbox and click delete button, it should access database and delete all checked item.
I have already tried numerous googled solution and never worked for me. here is short scenario
on my aspx page:
1)search by id text box, when user enter ID and click search button, the below table is displayed
<asp:GridView ID="MyGridView" runat="server">
<Columns>
<asp:TemplateField headertext="Name">
<ItemTemplate>
<asp:Label id="namelbl"
text='<%# Eval("name")%>' runat="server"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete Now?">
<ItemTemplate>
<asp:CheckBox Enabled="true" ID="chkStatus" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
after data is displayed, user checks the desired checkbox and click delete button, then the code behind is run
Protected Sub DelSelected(ByVal sender As Object, ByVal e As System.EventArgs)
Dim idList as ArrayList = new ArrayList()
For Each row As GridViewRow In MyGridView.Rows
Dim selectcb As CheckBox = CType(row.FindControl("chkStatus"), CheckBox)
If (selectcb.Checked) Then
'put into delete list
Trouble starts here, selectcb checkbox is always false
How could that happen, any idea would be appreciated
Thanks
you must bind your data only when no IsPostback in order to persist your checkbox selected, and no reset
If(! IsPostBack)
{
Bind();
}

Dropdownlist results in gridview

I'm having some trouble getting the results of the drop-downs in a gridview, and haven't found any helpful articles for VB code.
What I'm trying to do is build a site for tests. So far I have the gridview built w/the extra column for a drop-down list where the true/false answer will be selected. When the test is completed, there is a submit button. All is well except I need to be able to get the results of each drop-down list on post-back to a variable or array (each test contains 10 questions) so the results can be checked/graded. When the results are determined I would like to display a label in it's place and change the text value accordingly (correct or incorrect), so I'll need to be able to enumerate these as well (i.e. label1.text="Correct!", label2.text="Incorrect!", etc...).
Code so far.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" BackColor="White" BorderColor="#3366CC"
BorderStyle="None" BorderWidth="1px" CellPadding="1">
<RowStyle BackColor="White" ForeColor="#003399" />
<Columns>
<asp:BoundField DataField="Question" HeaderText="Question"
SortExpression="Question" />
<asp:TemplateField HeaderText="Answer">
<ItemTemplate>
<% If Not IsPostBack Then%>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlAnswer"
DataTextField="torf" DataValueField="torf">
</asp:DropDownList>
<%Else%>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<%End If%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
</asp:GridView>
The preceding code loads 10 rows, 2 columns (column1:Question | column2-[DropDownLists]:Answer). I'm a freshman when it comes to development, so if you need additional info let me know.
Here is how I handled it:
created a page level private variable to hold our list of correct/incorrect values
Private Answers as New List(Of Boolean) 'creates a strongly typed list of t/f values
in Page.Load
if IsPostBack then
'iterate through each row
for each gridRow As GridViewRow in GridView1.Rows
'get the selected value for this answer
Dim answer as string = CType(gridRow.FindControl("DropDownList1"),DropDownList).SelectedValue
'add this answer to the list
Answers.Add(IsCorrectAnswer(answer))
next
end if
the IsCorrectAnswer function determines whether or not the answer given for this question is correct and returns a Boolean value. You would need to write this function to suit your needs.
in Button1.Click handler
'rowCounter will act as an index to the answers
Dim rowCounter as Integer = 0
For Each gridRow as GridViewRow in GridView1.Rows
'grid_RowDataBound handles the binding of single row
grid_RowDataBound(gridRow, rowCounter)
rowCounter+=1
Next
finally
Private Sub grid_RowDataBound(gridRow as GridViewRow, rowCounter as Integer)
'make the dropdown invisible
CType(gridRow.FindControl("DropDownList1"),DropDownList).Visible = False
'because we'll be acting on two properties of the label, I shove it in a variable first for ease of access
Dim label As Label = CType(gridRow.FindControl("Label1"),Label)
'set the label to visible
label.Visible = True
'set the text
label.Text = Iif(Answers(rowCounter),"Correct", "Incorrect")
End Sub
Someone probably has a cleaner solution than this, but I do know this works, at least as far as I understand the issue you are facing.
Good luck
What about binding the Visible attribute to Page.IsPostBack (note this is in C# since I'm not familiar with the syntax for VB.NET... I'm sure something similar would work):
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlAnswer"
DataTextField="torf" DataValueField="torf" Visible='<%# !Page.IsPostBack %/>></asp:DropDownList>
<asp:Label ID="Label1" runat="server" Text="" Visible='<%# Page.IsPostBack %/></asp:Label>
</ItemTemplate>
check the RowDataBound event of the gridview object. It takes two parameters:
(byval sender as Object, byval e as GridViewRowEventArgs). With it, you can set the value of the label in each row to 'Correct' or 'Incorrect' on the postback.
see the example at
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx
for more information
as for getting the answers into a variable, here are a couple of options
1) check viewstate. It has some overhead, so be cautious with it.
2) save the data to a Session object

Resources