Tutorials » AspNet tutorials »

TextBox and Button controls in ASP.NET


This article explains how to use various properties and events associated with web controls like Textbox and Button.


In the previous chapters you learned how to create a new web form and add a label control to it. You also found how to change the properties of the Label control in design time and run time.

In this chapter, you learn the most frequently used controls - the Textbox and the Button controls.

Create a new webform



Let us start fresh by creating a new web page. Right click on the project name in the solution explorer and select Add > Add Web Form. Select the file name as 'WebForm2.aspx'.

Now you have a blank form. In the design mode, drag and drop two Label controls, one Textbox and one Button. Select each control and change the properties as shown below:

Label1:
======================
Id - lblMessage

Label 2:
======================
Id - lblLabel
Text - What is the current day?

Textbox
======================
Id - txtCurrentDay
Text - Monday

Button
======================
Id - btnSubmit
Text - Submit

Arrange the position of the controls so that they look as shown below:



Handling events in ASP.NET



Let us write an event handler for the click event of the Button control. All you have to do is, just double click on the button control in the designer. Visual Studio will automatically create an event handler for you, as shown below:


Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click

End Sub


Notice the Handles btnSubmit.Click. This statement says this is the method that handles the Click event for the button btnSubmit.

You can change the event handler name btnSubmit_Click() to whatever you want and it will still work as long as Handles btnSubmit.Click is there at the end of it.

Event Handlers - Difference between VB.NET and C#



The event handlers are created slightly different in C#. If you double click on a button in the web form in C#, Visual Studio will create the event handler as shown below:

private void btnSubmit_Click(object sender, System.EventArgs e)
{
}


Note that there is no Handles btnSubmit.Click in the end of the event handler declaration. Instead, there is another hidden lin as shown below:

this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);


The above line is hidden within the #region Windows Form Designer generated code. You may need to click on the + sign on the left end of the line #region Windows Form Designer generated code to view the hidden code in this region.

In C#, the line this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click); says which method need to be called when a button is clicked.

Handling events



Ok, now you have created an event handler for the button clicked event. Let us write some code.

What we are going to try is, get the text user typed in the Textbox and compare against the current day. If the day user typed matches with current day, we will display a success message in the label. If the day does not match, we will display an error.

Copy and paste the following code below to your event handler.

Dim userDay As String = txtCurrentDay.Text
Dim currentDay As String = DateTime.Today.DayOfWeek.ToString()

If userDay = currentDay Then
lblMessage.Text = "Great! You got it right."
lblMessage.ForeColor = Color.FromName("DarkGreen")
Else
lblMessage.Text = "Oops! You are wrong. Today is '" & currentDay & "'."
lblMessage.ForeColor = Color.FromName("Red")
End If


Here is the C# code, if you are working on C#.

string userDay = txtCurrentDay.Text;
string currentDay = DateTime.Today.DayOfWeek.ToString();

if (userDay == currentDay )
{
lblMessage.Text = "Great! You got it right.";
lblMessage.ForeColor = Color.FromName("DarkGreen");
}
else
{
lblMessage.Text = "Oops! You are wrong. Today is '" + currentDay + "'.";
lblMessage.ForeColor = Color.FromName("Red");
}


Please note that there is only syntax difference between C# code and VB.NET. So, here onwards, we will provide the example code only in one language.

Now let us run the web page to see how it works. You may need to right click on your form (WebForm2.aspx) and select 'Set as Start Page' so that when press 'Ctrl + F5', this new page will be launched instead of your default page.

Build and launch the web page. You will see the textbox appearing with the default value 'Monday'. Press the 'Submit' button. If your current day is a Monday, you will get a success message. Otherwise, you will see the error message.

The code is self explanatory. The call DateTime.Today.DayOfWeek.ToString() returns the current system day and you are comparing aginst the data typed by the user. You can retrieve the text typed by user by accessing the property txtCurrentDay.Text.

TextChanged event for Textbox in ASP.NET



Let us try to learn one more event called 'TextChanged' for the Textbox. This is not widely used, but let us do it for learning purpose.

Double click on the Textbox in the designer view. This will create the TextChanged event handler.

Simply copy paste the code from the button click event handler to this TextChanged event handler. Run the application and see.

You must press 'Tab' from Textbox to trigger the Textchanged event. But in our case, it will not fire the event even though we have written the event handler.

We have to do one more step to fire the Textchanged event. Go to the designer and see the properties of the Textbox. You must change the property 'AutoPostBack' to true. This is 'False' by default to avoid triggering Textchanged events unncessarily.

Also note that, the Textchanged event will be fired only if you change the current text in the Textbox. If you simply press 'Tab' by leaving the default value 'Monday' there, it will not be fired. Change it to 'Tuesday' and press 'Tab'. You can see that the Textchanged event handler is executed.

In windows programming, the textchanged event will fire when you type any character, not after you move out from the textbox control.

Write solid application



Did you notice that if you type 'monday' instead of 'Monday', it will not match? Let us modify our code so that it will work even if user type the correct day, with a different case.


if (userDay.ToUpper() == currentDay.ToUpper() )


Make a small change as shown above. Here we are converting the user typed text into all upper case. We are converting the system day also into upper case. So, whatever user typed does not matter. Everything is converted into upper. Now run the page and you will see that user can type in any case (upper or lower) and it will still match. If you take care of such small small things, you can write great applications.

Write re usable code



When you made the above change (if (userDay.ToUpper() == currentDay.ToUpper() ), you had to actually change in two places because you had copied and pasted the same code in two places.

You should never copy paste the same code in two places. Instead, you must move that code into a method and call the same method from both the places. This way, if you need to make any change, you need to make the change only once.

See the improved code:

Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
' Call the common method
ValidateUserData()
End Sub

Private Sub txtCurrentDay_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtCurrentDay.TextChanged
' Call the common method
ValidateUserData()
End Sub

' This is the common method which validates the user input and displays the result.
Private Sub ValidateUserData()
Dim userDay As String = txtCurrentDay.Text
Dim currentDay As String = DateTime.Today.DayOfWeek.ToString()

If userDay.ToUpper() = currentDay.ToUpper() Then
lblMessage.Text = "Great! You got it right."
lblMessage.ForeColor = Color.FromName("DarkGreen")
Else
lblMessage.Text = "Oops! You are wrong. Today is '" & currentDay & "'."
lblMessage.ForeColor = Color.FromName("Red")
End If
End Sub


This is a fundamental concept you have to learn. Always break your code into small small methods and call these methods in your application.



Next Chapter: ASP.NET Objects
Previous Chapter: Changing properties dynamically at run time
More Chapters: ASP.NET Tutorials
More Tutorials: Tutorial Index



Top Contributors
Today
    Last 7 Daysmore...

    Awards & Gifts

    Online Members

    Manigandan
    More...
     
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India