I have an ASP TextBox with TextMode set to MultiLine. I'm having problems with preserving the vbCrLf characters when a user tries to put line breaks into the text. When a button on the page is pressed, I'm taking the text from the control, trimming it using String.Trim, and assigning that value to a String property on an object (which, in turn assigns it to a private internal String variable on the object). The object then takes the value from the private internal variable and throws it into the database using a stored procedure call (the SP parameter it is put into is an nvarchar(4000)).
ASPX Page:
<asp:UpdatePanel ID="UpdatePanel2" runat="server" RenderMode="Inline" UpdateMode="Conditional"
ChildrenAsTriggers="true">
<ContentTemplate>
<!-- some other controls and things -->
<asp:TextBox TextMode="MultiLine" runat="server" ID="txtComments" Width="100%" Height="60px" CssClass="TDTextArea" Style="border: 0px;" MaxLength="2000" />
<!-- some other controls and things -->
</ContentTemplate>
</asp:UpdatePanel>
code behind:
ProjectRequest.StatusComments = txtComments.Text.Trim
object property:
Protected mStatusComments As String = String.Empty
Property StatusComments() As String
Get
Return mStatusComments.Trim
End Get
Set(ByVal Value As String)
mStatusComments = Value
End Set
End Property
stored proc call:
Common.RunSP(mDBConnStr, "ProjectStatusUpdate", _
Common.MP("#UID", SqlDbType.NVarChar, 40, mUID), _
Common.MP("#ProjID", SqlDbType.VarChar, 40, mID), _
Common.MP("#StatusID", SqlDbType.Int, 8, mStatusID), _
Common.MP("#Comments", SqlDbType.NVarChar, 4000, mStatusComments), _
Common.MP("#PCTComp", SqlDbType.Int, 4, 0), _
Common.MP("#Type", Common.TDSqlDbType.TinyInt, 1, EntryType))
Here's the strangest part. When I debug the code, if I type
"test
test"
(without the quotes) into the comments text box, then click the save button and use the immediate window to view the variable values as I step through, here is what I get:
?txtComments.Text
"test test"
?txtComments.Text.Trim
"test
test"
?txtComments.Text(4)
"
"c
?txtComments.Text.Trim()(4)
"
"c
Anyone have a clue as to what's going on here?
There are two problems at bay here. First, the immediate window in VB is converting the non-printable character to a space so you cannot see it. In C#, it will show the character using its replacement escape code (e.g. \n or \r\n), but VB does not. Second, VB sees the break as a line-feed only (vbLf) not a carriage-return+line-feed (vbCrLf). Thus, if you do the following in break mode in the immediate window you will see what I mean (assuming you type test, hit Enter, test in the comments box):
?txtComments.Text.Substring(4,1) = vbLf
True
May be, you should use Environment.NewLine constant to get replaced with the vbCrLf
Related
VS-Studio 2012 Web Express, ASP.NET, WebForms , VB , SqlServer , WebSite application having trouble saving a NULL value for DateTime to the strongly typed ROW:
Dim oRowVEHICLES As Main_TblAdap.tVEHICLESRow = odtVEHICLES.Rows(0) ' (0) is the first row.
oRowVEHICLES.[WElectrical] = If(WElectrical.Year < 10, DBNull.Value, WElectrical)
...etc...
Currently the DetailsView template field textbox is < blank> or empty or "" and the BLL function shows it as a date like: #01/01/0001#. So I test the YEAR value of the passed in variable if less than 10 then save DBNull.Value to the oRowVehicles.[WElectrical] but fails since datatype=Date and cannot convert DBNull to Date.
The DB-field is type Date and allows nulls.
The TableAdapter.xsd view shows the default value is < DBNULL>.
So, why is the oRowVehicles not Date nullable?
How do I make the WElectrical column nullable DATE?
I must be overlooking something, because I cannot be the only one to save an optional DATE value to the Sql-DB.
Your comments and solutions are welcome. Thanks...John
EDIT
ASPX code one DATE field in the DetailsView (others are similar):
<asp:TemplateField HeaderText="Electrical End Date" SortExpression="WElectrical">
<EditItemTemplate>
<TGADate:GADate ID="ucdtWElectrical" runat="server" Enabled="True" MinDate="01/01/1980" MaxDate="12/31/2050"
Caption="Electrical End Date" HideCaption="True" Width="100"
IsRequired="false"
UpdateMode="Conditional"
Text='<%# Bind("WElectrical")%>' />
</EditItemTemplate>
<InsertItemTemplate>
<TGADate:GADate ID="ucdtWElectrical2" runat="server" Enabled="True" MinDate="01/01/1980" MaxDate="12/31/2050"
Caption="Electrical End Date" HideCaption="True" Width="100"
IsRequired="false"
UpdateMode="Conditional"
Text='<%# Bind("WElectrical")%>' />
</InsertItemTemplate>
<ItemTemplate>
<asp:Label ID="lblWElectrical" runat="server" Text='<%# clsGA_Lib1.fnGetDateTextFromObject(Eval("WElectrical"))%>' Style="font-weight: bold;"></asp:Label>
</ItemTemplate>
<ItemStyle Font-Bold="true" />
</asp:TemplateField>
Object DataSource parameter definition in the ASPX.
<asp:Parameter Name="WElectrical" Type="DateTime" />
BLL Code:
<System.ComponentModel.DataObjectMethodAttribute(System.ComponentModel.DataObjectMethodType.Update, False)> _
Public Function UpdateFromDetailsView(ByVal original_UID_VEHICLE As Int32, _
ByVal VehicleNbr As String, _
...other function parameter variables...
ByVal WElectrical As Date, _
...other function parameter variables...
) As Boolean
' Get the new VEHICLE-row instance to be updated.
Dim odtVEHICLES As Main_TblAdap.tVEHICLESDataTable = Adapter.GetVhclByVhclID(original_UID_VEHICLE)
If odtVEHICLES.Count <> 1 Then
' no matching record found, return false
Return False
End If
' Populate the values of the ROW.
Dim oRowVEHICLES As Main_TblAdap.tVEHICLESRow = odtVEHICLES.Rows(0) ' (0) is the first row.
With oRowVEHICLES
...setting row-field values...
.[WElectrical] = If(WElectrical.Year < 10, Nothing, WElectrical)
...etc...
End With
' Update the oRowVEHICLES.
Dim rowsAffected As Integer = Adapter.Update(odtVEHICLES)
' Return TRUE if precisely one row was INSERTED, otherwise false.
Return CBool(rowsAffected = 1)
End Function
Edit comment for above code
The WElectrical parameter coming into the BLL-function is a DATE with a value of #01/01/0001#.
The code to place the value into the ROW-object
.[WElectrical] = If(WElectrical.Year < 10, Nothing, WElectrical)
places Nothing as the row-object-field-value.
The Adapter.Update(odtVEHICLES) updates the Sql-DB.
So what is causing the #01/01/0001# value to be placed into the Sql-DB?
Sql-DB column definition
//////// end of Edit ///////////
do one thing:
change DBNull.Value to Nothing
Alternatively you can change the datatype in the dataset to System.Object, and
go to the properties of that data colm
then you can select '(Nothing)' in the dropdown.
set Null value to >> Nothing
Thanks to all commentators to the above question.
The solution is to change the Row-column-variable to this sentence which casts the Nothing to Date? (nullable) as follows...
.[WElectrical] = If(WElectrical.Year < 10, CType(Nothing, Date?), WElectrical)
AND -- Changed the dataset-column-definition (in the .xsd) as follows:
DataType ==> System.Object (not Date)
NullValue ==> (Nothing) (not Throw Exception)
My sincere thanks to all contributors -- since elements of each of their suggestions have contributed to this solution.
This is the solution for sending a nullable value into the DataRow-column.
Thank you for all your help.
I read many topics about this but I'm having a problem with the Textmode = "Time" property on .NET 4.5, as well.
I have this on aspx side:
<asp:TextBox runat="server" ID="txtBoxStartTime" TextMode="Time"></asp:TextBox>
On vb.net side, when I try to get the Text value from this textbox, I have nothing but empty string ("").
CDate(txtBoxStartTime.Text)
On client-side, in webInspector I can easily take the value from the textbox, but I need it in server-side...
Even though I try with HTML5 tags with runat="server" I encounter the same problem.
I've noticed the problem is the same with all of the Textmode Property on Framework 4.5
Any suggestions/solutions on this?
I truly appreciate your input!
Thanks!
Use this Attribute: "format"
<asp:TextBox ID="txtTime" runat="server" TextMode="Time" format="HH:mm" />
it will return the format of 24 for hours.
if your value is 10:00 PM then in server side the (txtTime.Text) value will be "22:00".
I Test it in Chrome and it's work
TextBoxMode Enumeration
SingleLine mode displays the TextBox control as a single row. If the
user enters text that exceeds the physical size of the TextBox
control, the text will scroll horizontally. MultiLine mode displays
the height of the TextBox based on the Rows property, and allows data
entry on multiple lines. The text will automatically wrap if the Wrap
property is set to true. If the user enters text that exceeds the
physical size of the TextBox, the text will scroll accordingly and
scroll bars will appear. The behavior of Password mode is similar to
SingleLine mode except that all characters entered in the TextBox
control are masked and are not saved in view state.
and then
The remaining options correspond to type attribute values for the
input element in the HTML5 specification.
So there is not any change to server side behaviours of textbox, the following code works as expected
Markup
<asp:TextBox runat="server" TextMode="Time" ID="test"></asp:TextBox>
<asp:Button runat="server" ID="btn" Text="ok" />
C# code behind
protected void Page_Load(object sender, EventArgs e)
{
string value = test.Text;
}
Use the HH:mm time format:
Time.Text = SomeTime.ToString("HH:mm");
Have you tried placing this in your page_load?
txtBoxStartTime.Attributes["type"] = "Time"
So, to have an answer, here's the code it's on my Page.Load (for testing)
You can see there's not value on txtBoxStarTime.Text
For my situation, I have this inside an update panel:
<asp:TextBox runat="server" ID="txtBoxStartTime" TextMode="Time" Width="102px"></asp:TextBox>
<asp:TextBox runat="server" ID="txtBoxEndTime" TextMode="Time" Width="102px"></asp:TextBox>
<asp:Button CssClass="positive" ID="btnOtherSendRequest" runat="server" Text=" Send Request" ToolTip="The selected request would be sent to X" OnClick="btnOtherSendRequest_Click"/>
This is the code in VB.NET:
Protected Sub btnOtherSendRequest_Click(sender As Object, e As EventArgs)
Try
lblSubmitted.Text = ""
lblValidateNotInfo.Text = ""
hdnRequestType.Value = "OTH"
Dim messageSuccessful As String = "Thank you for submitting your Request(s)!"
Dim messageUnSuccessful As String = "The Request was not submitted due to some errors. Please 'Go Back' and re-send!"
Select Case ddlRequest.SelectedValue
Case "18" ' Schedule Update Call
If Not (txtBoxStartDate.Text.Length > 0 And txtBoxEndDate.Text.Length > 0 And IsDate(txtBoxStartDate.Text) And IsDate(txtBoxEndDate.Text)) Then
' AI - if dates are in invalid format
ScriptManager.RegisterStartupScript(Me, Me.GetType, "AlertScript", "alert ('Please make sure the dates are in a valid format!');", True)
Exit Sub
ElseIf Not CDate(txtBoxStartDate.Text).CompareTo(Date.Now) > 0 Then
' AI - Start Date must be greater than today.
ScriptManager.RegisterStartupScript(Me, Me.GetType, "AlertScript", "alert ('""Start"" date must be a future date!');", True)
Exit Sub
ElseIf Not CDate(txtBoxEndDate.Text).CompareTo(CDate(txtBoxStartDate.Text)) >= 0 Then
' AI - Start Date must be greater than today.
ScriptManager.RegisterStartupScript(Me, Me.GetType, "AlertScript", "alert ('""End"" date must be the same as the ""Start"" date or a date after the ""Start"" date!');", True)
Exit Sub
ElseIf CDate(txtBoxStartDate.Text).DayOfWeek = DayOfWeek.Saturday Or CDate(txtBoxStartDate.Text).DayOfWeek = DayOfWeek.Sunday Or CDate(txtBoxEndDate.Text).DayOfWeek = DayOfWeek.Saturday Or CDate(txtBoxEndDate.Text).DayOfWeek = DayOfWeek.Sunday Then
ScriptManager.RegisterStartupScript(Me, Me.GetType, "AlertScript", "alert ('Weekends excluded!');", True)
Exit Sub
Else
lblSubmitted.Text = messageSuccessful
End If
Case "19" ' Request Training Call
Case "20" ' Request Call from Cust. Service
Case "21" ' Other Request
If txtBoxOther.Text <> "" Then
lblSubmitted.Text = messageSuccessful
Else
lblSubmitted.Text = messageUnSuccessful
ScriptManager.RegisterStartupScript(Me, Me.GetType, "AlertScript", "alert ('Please enter your request into the textarea first!');", True)
txtBoxOther.Focus()
Exit Sub
End If
End Select
Call sendRequest()
Call JSEffect(True)
Catch ex As Exception
lblMessage.Text = "Error when taking the request to be inserted - " & ex.Message
Finally
hlServCenterPend.Text = "Pending Requests (" & getServCenterStatus("PEND").ToString & ")"
hlServCenterComp.Text = "Completed Requests (" & getServCenterStatus("COMP").ToString & ")"
End Try
End Sub
And Here I got the error:
Public Sub sendRequest(Optional pid As Integer = 0, Optional claim As Integer = 0, Optional insured As Integer = 0)
Dim req As New cls_services.request
Try
req.clinicID = CInt(MyMod.FetchStoredData("ClinicID"))
req.pid = pid
req.type = CInt(ddlRequest.SelectedValue)
Select Case req.type
Case 1, 11, 12, 13, 14
req.status = "COMP"
Case Else
req.status = "PEND"
End Select
req.claimID = claim
req.insuranceID = insured
req.dueDate = req.getDueDate(req.type)
req.other = Trim(txtBoxOther.Text)
Select Case req.type
Case 18
req.fromDate = CDate(txtBoxStartDate.Text)
req.fromTime = CDate(txtBoxStartTime.Text)//ERROR HERE! - EXCEPTION
req.toDate = CDate(txtBoxEndDate.Text)
req.toTime = CDate(txtBoxEndTime.Text)
End Select
req.fax = Trim(txtFaxTreatmentRecords.Text)
req.createUser = Request.ServerVariables("AUTH_USER")
My solution here, is trying to store the value from textbox in a hiddenfield, then access in codebehind... but it is still a "last-measure" solution.
The fact is, as I said - On PostBack - the "Text" value disappears. Don't know why.
Still waiting for suggestions! :)
So,
I've been struggling with this for some hours. I did not find any "code-behind" solution. So I come with a solution. Maybe it will help you in some ways:
Using JavaScript to store the value into a hiddenfield, like this:
<asp:TextBox runat="server" ID="txtBoxStartTime" TextMode="Time" Width="102px" onchange="storeStartTime()"></asp:TextBox>
<asp:HiddenField runat="server" ID="hdnStartTime"/>
JavaScript Function:
function storeStartTime() {
var x = document.getElementById("ctl00_mainPageBody_txtBoxStartTime");
var y = document.getElementById("ctl00_mainPageBody_hdnStartTime");
y.value = x.value;
alert(y.value);
}
Hope it will help if you encounter this problem!
I have found heaps of solutions for this in C# but when you are dealing with FindControls and trying to pull a value out of the GridView the C# doesn't help and the translated code doesn't work.
I have this gridview:
<asp:GridView ID="WIPListGrid" runat="server" DataSourceID="WIPDataSource"
CssClass="site" AutoGenerateColumns="False"
Width="95%" DataKeyNames="Masterid_Action" onrowdatabound="WIPListGrid_RowDataBound">
<Columns>
<asp:BoundField DataField="Action Due Date" HeaderText="Action Due Date"
SortExpression="Action Due Date" />
</Columns>
</asp:GridView>
and I have this in vb:
Protected Sub WIPListGrid_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles WIPListGrid.RowDataBound
Dim DueDate As Label = DirectCast(e.Row.FindControl("Action Due Date"), Label)
'do what ever you want to do here using the value of your label
MsgBox("Due Date = " & DirectCast(e.Row.FindControl("Action Due Date"), Label))
End Sub
Error message is Operator & is not defined for types 'String' and 'System.Web.UI.WebControls.Label'
This is a remedial example of what I ~really~ want to do. Above I just want to display what is contained in DueDate to see what format it is in so I can test it against other values. but it won't work. It appears the the contents of Action Due Date is not a string... so, what am I missing?
I have tried to set the value equal to a string but got the same problem, the Label isn't a string...
How do I find out what's in there in order to evaluate it?
17/01/2013 edit: Keeping this active as I still do not have my issue resolved.
18/01/2013 edit:
vb.net code is now
Protected Sub WIPListGrid_ROWDataBound(sender as Object,
e As System.Web.UI.Webcontrols.GridViewRowEventArgs) Handles WIPListGrid.RowDataBound
Dim DueDate As Label = DirectCast(e.Row.FindControl("Action Due Date"), Label)
'do what ever you want to do here using the value of your label
MsgBox("Due Date = " & DueDate.Text)
End Sub
But now I get an error that the Object isn't instantiated and its pointing to the msgbox line in the code. I thought that I instantiated it when I dim it as a Label...
The official error is:
"Object reference not set to an instance of an object."
the troubleshooting tips say to
1) Use the "new" keyword to create an object instance
2) Check to determine if the object is null before calling the method
I tried the "new" option and got an error that says the variable has already been declared.
So now I want to check to determine if the object is null and can't figure out how.
I've tried testing: DirectCast(e.Row.FindControl("action due date"), Label) <> ""
but got an error: Overload resolution failed because no accessible '<>' can be called with these arguments.
How do I test to see if the object is null?
The value shouldn't be null (the database doesn't allow it to be null), BUT this could be the crux of my issue...
Any help?
When working with controls, you have to point out that you want that value inside your control.
In your case, you're just going for the label-control itself (not the text inside).
For example:
Dim myControl As Label = DirectCast(e.Row.FindControl("myControl"), Label)
MsgBox("MyText = " & myControl.Text)
Hope this helps.
The problem is you are using a BoundField so there is no control to find. Change it to a templatefield and this will work.
<asp:GridView ID="WIPListGrid" runat="server" DataSourceID="WIPDataSource"
CssClass="site" AutoGenerateColumns="False"
Width="95%" DataKeyNames="Masterid_Action" onrowdatabound="WIPListGrid_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Action Due Date">
<ItemTemplate>
<asp:Label ID="lblActionDueDate" runat="server" Text='<%# Bind("[Action Due Date]") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
For Your Row DataBound Event use
Dim DueDateLabel As Label = DirectCast(e.Row.FindControl("lblActionDueDate"), Label)
'Check Label Exists
If DueDateLabel IsNot Nothing Then
Dim DueDateText As String = DueDateLabel.Text
MsgBox(String.Format("Due Date {0}", DueDateText))
End If
I have a salary TextBox and an associated CompareValidator, which is setup as follows:
<asp:CompareValidator ... Operator="DataTypeCheck" Type="Currency" />
I fill the TextBox with a formatted string out of the database:
txtSalary.Text = myObject.Salary.ToString("N2")
When a user accesses the page using a French culture (such as fr-ca), the ToString method will put 80 000,00 in the textbox, which is fine.
However, any number with a space in it causes the validator to fail, which is not fine. Is there any way to make the CompareValidator work properly with non-US formatted numbers?
I had a problem like you, but not quite the same, I had something like this:
<asp:RangeValidator ID="rw" ErrorMessage="error"
Text="!" ControlToValidate="r" MinimumValue="1 000,00" MaximumValue="1 000 000,00" Type="Currency" CultureInvariantValues="false" runat="server" EnableClientScript="true" />;
I databound my controls with data for example 2 000,00 and I had validation error
but when I entered a value od 2 000,00 everything was OK.
the answer was space in CurrencyGroupSeparator, my culture pl-pl has space in it, but it is not space "\x0020" but it is non breaking space "\00A0"
I've used reflector to do some digging and what I found is puzzling
currency format check is in BaseCompareValidator class in method
private static string ConvertCurrency(string text, NumberFormatInfo info)
and in code there is a line like this:
if (currencyGroupSeparator[0] == '\x00a0')
{
currencyGroupSeparator = " ";
}
I putted decompiled code in test project and tried to run it, and indeed code was not working properly.
ConvertCurrency(10000000.00m.ToString("n"), NumberFormatInfo.CurrentInfo)
returned null;
why someone put it there I don't know, but then I commented it, method have started work properly.
we cant compile .net framework from source yet, so what we can do, is to change separator from non breaking space to space
so the solution to our problem is:
Thread.CurrentThread.CurrentCulture = new CultureInfo("some culture
name");
Thread.CurrentThread.CurrentCulture.NumberFormat.CurrencyGroupSeparator
= "\x0020"; Thread.CurrentThread.CurrentCulture.NumberFormat.NumberGroupSeparator
= "\x0020";
I guess it is just a bug with the CompareValidator and RangeValidator - likely on the client side JavaScript.
I fixed the problem by changing to a CustomValidator, with the following code on the server side (and no code on the client side):
Protected Sub ValidateSalary(ByVal sender As Object, _
ByVal e As ServerValidateEventArgs)
Try
If txtSalary.Text <> String.Empty Then
Dim salary As Decimal = Convert.ToDecimal(txtSalary.Text, _
Thread.CurrentThread.CurrentUICulture)
End If
e.IsValid = True
Catch ex As Exception
e.IsValid = False
End Try
End Sub
I have a page on which there are two textboxes that have a regular expression on them.
ASPX Code TextBox 1
<asp:TextBox ID="txtCasesInsert" runat="server" Width="50px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvCases" ControlToValidate="txtCasesInsert" ValidationGroup="InsertRecord"
runat="server" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexCases" ControlToValidate="txtCasesInsert"
ValidationExpression="[0-9]+(,[0-9]+)*" ForeColor="Red" ErrorMessage="Please seperate numbers with a comma"
runat="server" />
ASPX Code TextBox 2
<asp:TextBox ID="txtPremiumInsert" runat="server" Width="50px"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvPremium" ControlToValidate="txtPremiumInsert"
ValidationGroup="InsertRecord" runat="server" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="regexPremium" ControlToValidate="txtPremiumInsert"
ValidationExpression="[0-9]+(,[0-9]+)*" ForeColor="Red" ErrorMessage="Please seperate numbers with a comma"
runat="server" />
The regular expression works as intended for both text boxes.
What I need now is to be able to check the text being inputted into those text boxes and if the regular expression is valid, then enable my Insert button, otherwise, keep the button disabled.
Insert Button
<asp:Button ID="btnInsertRecord" Width="100px" Height="25px" runat="server" Text="Add Record"
CssClass="buttonBlue" ValidationGroup="InsertRecord" />
The reason I want to do this, is because when the regex has an error, the page still allows the user to insert data so I thought of disabling the button if the regex isn't successfull to prevent this.
I tried this C# If regex doesn't match then do something and I've also read up on Microsofts Regex documentation to learn more about what I can do with Regex's but I haven't found any information related to what I need.
I also tried creating a function with a TextChanged method hooked onto the textboxes but it didn't work. No error messages, just the button wasn't disabling when I inputted a wrong string. That's the problem I'm also having now with my current code. It's like nothing is happening. I've hooked the debugger on the _premiumMatch.Success line but again, nothing is happening, it just lets me proceed. When I created the TextChanged method for my button, I also tried adding it into my Page Load method but that disabled the button straight away.
Current VB Code (Example with one of the text boxes)
Dim _regex As Regex = New Regex("[0-9]+(,[0-9]+)*")
Dim _premiumMatch = _regex.Match(txtPremiumInsert.Text)
If _premiumMatch.Success Then
Try
Company.Applications.ProductionEngine.BusinessAccess.ExcelFileContentUploadBusinessAccess.InsertLimitInsurance(_branch,
_premium,
_cases,
_ddlMonths,
_ddlYear)
Catch ex As Exception
InformationBox.ShowErrorMessage("Record not added. Please try again")
End Try
loadLimitInsurances()
InformationBox.ShowSuccessMessage("New Record Inserted")
txtBranchInsert.Text = ""
txtPremiumInsert.Text = ""
txtCasesInsert.Text = ""
End If
Not sure what I'm doing wrong. Any suggestions? The above VB code, for now is in my buttons click event but even with an invalid regex, when I click the insert is still performed.
First Edit
Just tried calling the below function in my page load but the button disables straight away and does not become enabled if I input a valid regex. Again, example is for one textbox.
Protected Friend Sub CheckPremium() Handles txtPremiumInsert.TextChanged
Dim _regex As Regex = New Regex("[0-9]+(,[0-9]+)*")
Dim _match As Match = _regex.Match(txtPremiumInsert.Text)
If _match.Success Then
btnInsertRecord.Enabled = True
Else
btnInsertRecord.Enabled = False
End If
End Sub
Second Edit
I have tried the above code and I've activated AutoPostBack on the textbox and still when I type an invalid expression it postbacks and activates my button.
Try this code:
Dim _regex As Regex = New Regex("[0-9]+(,[0-9]+)*")
Dim FoundMatch As Boolean = _regex.IsMatch(textPremiumInsert.Text)
If FoundMatch = True Then
Try
Company.Applications.ProductionEngine.BusinessAccess.ExcelFileContentUploadBusinessAccess.InsertLimitInsurance(_branch,
_premium,
_cases,
_ddlMonths,
_ddlYear)
Catch ex As Exception
InformationBox.ShowErrorMessage("Record not added. Please try again")
End Try
loadLimitInsurances()
InformationBox.ShowSuccessMessage("New Record Inserted")
txtBranchInsert.Text = ""
txtPremiumInsert.Text = ""
txtCasesInsert.Text = ""
End If
The code above uses the Regex.IsMatch method to compare the string passed with the regex pattern. It returns true if the string matches the Regex pattern.