Morning All,
I would like to have a cancel button on my web page that essentially i would like to clear form field and themn redirect users to the home page.
I have 7 txt boxes that i will need to clear before the page redirects. I have done some searching on the internets and have tried to put the following sample into my page with no luck....
With this code i get an error on the X = "" line. I get a message 'Value of type string cannt be converted to system.we.UI.control'
Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
Dim x As Control
For Each x In Me.Controls
If TypeOf x Is TextBox Then
x = " "
End If
Next
End Sub
And i have also tried the below which also produces a Compilation Error.
For Each c As Control In Me.Controls
If TypeOf c Is TextBox Then
DirectCast(c, TextBox).Text = ""
End If
Next
Can anyone help me with resolving this issue?
Regards
Betty
Try this:
Dim x As Control
For Each x In Me.Controls
If TypeOf x Is TextBox Then
Dim txt as TextBox = x
txt.Text = ""
End If
Next
Explanation:
You tried to set a string to a Control-variable and of course the compiler does not know how to to this.
The version I gave will set the Text-property of each TextBox to the empty-String
You can use html code to reset all field of current form you are working with
use follwoing code to reset all fields
<input type="reset" value="Clear" onclick="redirectFunction()" />
and in redirectFunction write following javascript code:
function redirectFunction()
{
window.location="destination.aspx";
}
using above code you can redirect to destination page.
Related
What I am trying to do is create a conditional statement that will alert the user if a text box is changed after initially filling that field.
For instance if they enter their name into the text box and then at a later point enter a different name into that text box, I want it to alert the user.
Below is my code of both the text box control as well as a .textchanged event.
Text Box Control:
<div class="txtSearch">
<asp:TextBox ID="txtSearchOC" runat="server" Width="250px" Text="" AutoPostBack="True" TabIndex="13" Font-Bold="True"
ForeColor="#822402" BorderColor="#822402" AutoCompleteType="Disabled" ClientIDMode="Static" />
</div>
.textChanged Event Code:
Protected Sub txtSearchOC_TextChanged(sender As Object, e As EventArgs) Handles txtSearchOC.TextChanged
Dim searchOCText As String = txtSearchOC.Text
Dim isTheSame As Boolean = False
If searchOCText = txtSearchOC.Text Then
isTheSame = True
End If
If isTheSame = True AndAlso searchOCText <> txtSearchOC.Text Then
Call txtSearchOC_Warning()
End If
End Sub
My thought process was to store the first name in a variable called "searchOCText" and then have a boolean that would hold true if searchOCText = txtSearchOC.Text, I would then use that boolean value to test if the text in the text box had changed, but I'm not terribly sure where to go from here as I am pretty new to programming.
So far I have tested the procedure "txtSearchOC_Warning()" and on its own it works and displays the message I am wanting to display. However when I try to call it from the TexChanged procedure nothing happens and I am at a loss as to why. So I am left to believe that the problem lies within my conditional and that I need to start digging there.
Any and all help would be greatly appreciated.
It's better to use JS to perform this validation since it's more efficient and doesn't require a PostBack to trigger. Check the following simple script:
<script>
let oldVal=document.getElementById("<%=txtSearchOC.ClientID%>").value;
function checkChange(val) {
if(oldVal!="")//To check if this change is a first time change
{
alert("The input value has changed to: " + val);
}
oldVal=val;
}
</script>
And your Text Box definition will be:
<asp:TextBox ID="txtSearchOC" runat="server"
onClientClick="checkChange(this.value)" AutoPostBack="false" ...
The problem with your approach is that searchOCText will be always equal to txtSearchOC after the PostBack. Line Dim searchOCText As String = txtSearchOC.Text
If you still want to use this approach you may store searchOCText in a Session like this:
Try
If Session("searchOCText").ToString()= txtSearchOC.Text Then
isTheSame = True
End If
Catch
End Try
Session("searchOCText")=txtSearchOC.Text
Looks like your code has some small mistakes:
TextChanged raised on programmatically setting value and any typing, every stroke. Better to use the LostFocus event.
Variable isTheSame is redundant (always True) because the event raises after text changing.
Actually, your message will never be shown when changing the user contents or not, because you compare user input with the same user input (inequality searchOCText <> txtSearchOC.Text always be False).
I think it is the simplest solution.
Public Class ExtTextBox
Inherits TextBox
Private LastUserInput As String
Protected Sub ExtTextBox_LostFocus(sender As Object, e As EventArgs) Handles Me.LostFocus
Select Case True
Case LastUserInput Is Nothing
LastUserInput = Text
Case Text <> LastUserInput
If MsgBox("Apply change?", MsgBoxStyle.YesNo Or MsgBoxStyle.Question) = MsgBoxResult.Yes Then
LastUserInput = Text
Else
Text = LastUserInput
End If
End Select
End Sub
End Class
Variable LastUserInput (initially Nothing) stores user input.
The first branch of Select Case stores the first user input in LastUserInput.
The second branch updates stored input or restored text according to user decision where the user points to any other element after any edit excluding the first one. You can put any code into the second branch to process new input.
I'm currently working on coding a web page for a school project. This site is supposed to be a simple online store where people can order prints of artwork. The specific page I'm working on has a Drop Down List (ddlArt) that is bound to my database and displays a list of the different art pieces available. When the user selects one of the items, all the information on that item is pulled from the database and displayed on the page in a variety of labels and such. The only thing is that I'm getting a null reference exception error saying "Object reference not set to an instance of an object" when I go to try to run the page. I got the same error on a homework assignment earlier in the year and managed to get it fixed, but I can't remember what I did and I can't get help from school until next week, so I thought I'd try my luck on here. Here's my code:
Private selectedArt As Art
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
ddlArt.DataBind()
End If
selectedArt = Me.GetSelectedArt
lblArtID.Text = selectedArt.ArtID()
lblArtName.Text = selectedArt.ArtName()
lblCaption.Text = selectedArt.Caption()
lblDescription.Text = selectedArt.Description()
imgArt.ImageUrl = "~/images/" & selectedArt.FileName()
End Sub
Private Function GetSelectedArt() As Art
Dim artTable As DataView = CType(SqlDataSource1.Select(DataSourceSelectArguments.Empty), DataView)
artTable.RowFilter = "ArtID = '" & ddlArt.SelectedValue & "'"
Dim artRow As DataRowView = artTable(0)
Me.imgArt.ImageUrl = "~/images/" & artRow("FileName")
Dim art As New Art
art.ArtID = artRow("ArtID").ToString
art.ArtName = artRow("ArtName").ToString
art.Caption = artRow("Caption").ToString
art.Description = artRow("LongDescription").ToString
art.FileName = artRow("FileName").ToString
Return art
End Function
And here's the code for the Art class, in case anybody is interested:
Public Class Art
Public Property ArtID As Integer
Public Property ArtName As String
Public Property ArtType As String
Public Property Caption As String
Public Property FileName As String
Public Property Description As String
End Class
When I get the error, it highlights the artTable.RowFilter = "ArtID = '" & ddlArt.SelectedValue & "'" line in the GetSelectedArt function. I've tried comparing it to my corrected homework assignment that I mentioned, but I can't seem to find the problem. My VB is a little fuzzy because it's been awhile since I actually took the class. Any suggestions? Thanks a bunch!
If I understand your comment above correctly, on the initial page load there is nothing in the ddlArt, because the user must first choose an art type.
If that is correct, then your answer to my question is your answer.
For whatever reason (and without seeing at least the Select statement), artTbl is not getting instantiated, which is why you're seeing the Object reference not set to an instance of an object error.
One way to fix this (without knowledge of your SqlDataSource it's hard to give a precise answer) is to modify your Page Load method so that GetSelectedArt is only called when the user has selected an item from the drop down list. Right now GetSelectedArt is called every time the page loads.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
ddlArt.DataBind()
Else
selectedArt = Me.GetSelectedArt
lblArtID.Text = selectedArt.ArtID()
lblArtName.Text = selectedArt.ArtName()
lblCaption.Text = selectedArt.Caption()
lblDescription.Text = selectedArt.Description()
imgArt.ImageUrl = "~/images/" & selectedArt.FileName()
End If
End Sub
However, the above modification will only prevent GetSelectedArt from being called on the initial page load. If your SqlDataSource.Select command is still returning nothing, then you're still going to have this problem.
A better solution would be to call the GetSelectedArt on the ddlArt.SelectedIndexChanged event handler. This way you'll know that you have (or should have) a valid SelectedValue from ddlArt.
Also, if you don't populate the drop down until the user selects an art type from the radio button list, why are you binding the drop down list on the initial page load (and what are you binding it to)? Or is the drop down list and detail information on a different page from the radio button list?
May be .. with ArtID as integer
artTable.RowFilter = "ArtID = " & format(ddlArt.SelectedValue)
I'm writing an ASP web application with VB back-end. What I'd like to do is generate a url and display this in control on the page. For example if I have a label and a button on the form. The label is blank. When the button is clicked the following code fires:
Protected Sub btnGenerate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGenerate.Click
label1.Text = "Hello"
End Sub
What I'd like to have is a url that would point to my ASP Page with the words "Hello" in the label. Is this possible?
You could do the following:
{siteaddress}/aspxpage.aspx?label=hello
then in you aspx page do something like:
<asp:label runat="server" id="yourLabelId" text='<%=Request.QueryString("label")%>' />
Or in the Page_Load:
yourLabelId.Text = Request.QueryString("label")
I would recommend validating the data before just writing it into the page.
Pass the text in query string e.g. suppose relative path of the page is /pagename.aspx , you can pass the query string as per given example below:
/pagename.aspx?text=hello
in c# write following code in Page_Load event
//You don't have to check the url all the time , so just check it if page is not posting back (first time after user visits the page and ignore all other same page post backs. Label can maintain its control state (text value) after every postback, so assign it only once to increase performance
if (!IsPostBack)
{
//Check if query string is provided or not , if it is not provided take some default text, I am taking empty string as default text.
string givenText = (Request.QueryString["text"] == null)?"":Request.QueryString["text"];
label1.Text = givenText;
}
You can also create a property for text given through query string and default text.
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'm sure this question has been asked a million times, however I haven't been able to find an answer that solves my problem.
I am programmatically adding some custom user controls to a PlaceHolder which I have on a simple aspx page. All of the user controls Postback's work correctly except for one which has a Gridview on it.
For some reason any postback that gets fired from within this control, does not call the specified event on the first click, however all future clicks it will work fine. I have no idea why this is the case, but many solutions I have found, suggest adding an ID to the ascx User Control, however this doesn't work in my case.
I've taken a look at the source file for the page that gets generated before and after the first click, javascript used for calling the postback changes, i.e
Before first click: onclick="javascript:__doPostBack('tmpControlID$sgvPrimaryEmploymentHistory','Select$0')"
After first click: onclick="javascript:__doPostBack('OFFHome1$tmpControlID$sgvPrimaryEmploymentHistory','Select$0')"
OFFHome1 is the parent user control which exists on the aspx page. All other controls are added to a placeholder in this control, i.e.
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="OFFHome.ascx.vb" Inherits="UmbracoUserControls.OFFHome" %>
<asp:PlaceHolder ID="phOFFSection" runat="server"></asp:PlaceHolder>
Nothing to complicated. Then in the code behind the controls are loaded into the placeholder using the following:
Private Sub LoadNextOFFStep()
Dim ControlName As String = "TestControl.ascx"
phOFFSection.Controls.Clear()
If ControlName IsNot Nothing AndAlso ControlName <> String.Empty Then
Dim NewControl As Object = LoadControl(ControlName)
With NewControl
.ID = USERCONTROLNAME
Dim StepCompleted As Boolean = .FillControl()
If StepCompleted Then
Exit Sub
End If
Dim AllowSkip As Boolean = .AllowSkip()
btnSkip.Visible = AllowSkip
End With
phOFFSection.Controls.Add(NewControl)
End If
End Sub
Again, nothing overly complicated. The USERCONTROLNAME is just a const with the value "tmpControlID" in it.
The control that is giving me trouble is a little complicated, I was originally using a custom GridView control that we have created, but have removed it and replaced it with the standard asp one to see if the problem still occurs, and it does.
Any button, on control which fires off a postback will fail the first time, and all future click will work correctly. On the first click the Page_Load event will get called, but that is it.
What am I doing wrong??
After far too much time spent on this, I have finally worked it out.
It was to do with the order of events, however just not where I had thought. The FillControl function was getting called before User Control had been added to the PlaceHolder. I changed this so that it gets called after the User Control was added to the PlaceHolder and now it works first time.
Basically the code looks like this now:
Private Sub LoadNextOFFStep()
Dim ControlName As String = "TestControl.ascx"
phOFFSection.Controls.Clear()
If ControlName IsNot Nothing AndAlso ControlName <> String.Empty Then
Dim NewControl As Object = LoadControl(ControlName)
With NewControl
.ID = USERCONTROLNAME
Dim AllowSkip As Boolean = .AllowSkip()
btnSkip.Visible = AllowSkip
End With
phOFFSection.Controls.Add(NewControl)
Dim StepCompleted As Boolean = CType(phOFFSection.Controls(0), Object).FillControl()
If StepCompleted Then
LoadNextOFFStep()
Exit Sub
End If
End If
End Sub
Thanks for everyone's help.
Well... the answer to the first question is simple: It fails the first time because the ID of the control (or rather, in the postback script) is different on subsequent page loads. It works on subsequent clicks because the control ID stays the same.
Now as to WHY that is... much tougher! But probably something to do with the order of operations here.
Try explicitly setting the NamingContainer value for NewControl:
With NewControl
.NamingContainer = OffHomeOne; // whatever
.ID = USERCONTROLNAME