Wednesday, September 11, 2013

ASP.Net Tutorial Series II



Adrotator control in asp.net

Adrotator control is used to display random ads. The ads information can be stored in an xml file or in a database table. In this video we will discuss about using an XML file.

XML file attributes ImageUrl - The URL of the image to display
NavigateUrl - The URL to navigate to, when the ad is clicked
AlternateText - The text to use if the image is missing
Keyword - Used by the adrotator control to filter ads
Impressions - A numeric value (a weighting number) that indicates the likelihood of how often the ad is displayed. 

Create an asp.net web application project, and add an XML file. Name the XML file as AdsData.xml. Copy and paste the following in the XML file. <?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
  <Ad>
    <ImageUrl>~/Images/Google.png</ImageUrl>
    <NavigateUrl>http://google.com</NavigateUrl>
    <AlternateText>Please visit http://www.Google.com</AlternateText>
    <Impressions>10</Impressions>
  </Ad>
  <Ad>
    <ImageUrl>~/Images/Pragim.png</ImageUrl>
    <NavigateUrl>http://pragimtech.com</NavigateUrl>
    <AlternateText>Please visit http://www.pragimtech.com</AlternateText>
    <Impressions>20</Impressions>
  </Ad>
  <Ad>
    <ImageUrl>~/Images/Youtube.png</ImageUrl>
    <NavigateUrl>http://Youtube.com</NavigateUrl>
    <AlternateText>Please visit http://www.Youtube.com</AlternateText>
    <Impressions>40</Impressions>
  </Ad>
</Advertisements>



Create an Images folder in the project, and add the following images. https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixmVSTmsi1NzHn_j7ECa7aZW6eppjMcfsNwnihPhnSY-6xRvZtJ_GBqoDnylzxxkjWQlFfE9TZ-XUbCb0efWJF3jBXagQL-4MClDT3kk6ROZnQKmo_LDAbGuKzzg1FqpJWNvIwXTOP0de2/s400/Google.png
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi02ujDpTQHoYeasWvBe6p-7AHh4eiuhetaTefGOqUvvD6y8-sKQs8eDlrOi4_rapG1X6peFBR5ZHmRIYeAeXRpshDB5hhnBqQ7HFJNN0y2NmvVuiWmrjNoOFY8Ulh4LX8Vx8IvsKtf8JLd/s400/Pragim.png

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLSYd2j-mqbbIDDN9AtZ7A46N-aEYXT_SKytn1G3B599Bu4fVbtoRvgJyN-Z_e7FBI5ouNiKW7Z-w8LtfgE5gtbLMW_Kco1-o_fuTvwTlHGqsSjVs7wvtA0KHpSOn0M_AoPX3aCroSbz2G/s400/Youtube.png

Drag and Drop the AdRotator control on the webform. Set AdvertisementFile="~/AdsData.xml". <asp:AdRotator AdvertisementFile="~/AdsData.xml" ID="AdRotator1" runat="server" />

To open the target web page in a separate browser window, set Target="_blank"

Use KeyWord attribute to filter ads.
The KeywordFilter and AdvertisementFile properties can be changed at runtime also. Changing the KeywordFilter at runtime could be very useful. For example, when the AdRotator control is on a master page, and if you want to change the KeywordFilter on each content page based on the keyword density, so that, only the ads targeting the page content can be displayed. More on this, when we discuss about master pages in a later video session.
Asp.net calendar control
In this video we will learn about the asp.net calendar control. Any time you want your users of the application, to provide a date, it is better to provide a calendar control from which they can select the date. In this session we will see how to do it.



Drag and drop a TextBox, ImageButton and a Calendar control on the webform. Create an Image folder and add the following Calendar.png to the Images folder.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjh9JyODanxw1p2eXdixea5Ikkn7ZW1mjOO6alEA4VQi_3WWIp5JQUmR7oHbn-vztk0piJRfMdBTMsZTsGECEfOHx-ZRHUd_NS1JYsubKxB_c5NDhnFw6i3qj_h9lTR9Lx95PSRTxUiGSnb/s1600/Calendar.png

Set the ImageUrl property of the image button to Calendar.png ImageUrl="~/Images/Calendar.png"

HTML of the ASPX page <asp:TextBox ID="TextBox1" runat="server" Width="115px"></asp:TextBox>
<asp:ImageButton ID="ImageButton1" runat="server"
    ImageUrl="~/Images/Calendar.png" onclick="ImageButton1_Click" />
<asp:Calendar ID="Calendar1" runat="server" ondayrender="Calendar1_DayRender"
    onselectionchanged="Calendar1_SelectionChanged"></asp:Calendar>



Code-Behind page code protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Calendar1.Visible = false;
    }
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
   
if (Calendar1.Visible)
    {
        Calendar1.Visible =
false;
    }
   
else
    {
        Calendar1.Visible =
true;
    }
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    TextBox1.Text = Calendar1.SelectedDate.ToShortDateString();
    Calendar1.Visible =
false;
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
   
if (e.Day.IsWeekend || e.Day.IsOtherMonth)
    {
        e.Day.IsSelectable =
false;
        e.Cell.BackColor = System.Drawing.
Color.LightGray;
    }
}

Date Conversion methods Response.Write("ToString() - "
+ DateTime.Now.ToString() + "<br/>");
Response.Write(
"ToLongDateString() - " + DateTime.Now.ToLongDateString() + "<br/>");
Response.Write(
"ToShortDateString() - " + DateTime.Now.ToShortDateString() + "<br/>");
Response.Write(
"ToLongTimeString() - " + DateTime.Now.ToLongTimeString() + "<br/>");
Response.Write(
"ToShortTimeString() - " + DateTime.Now.ToShortTimeString() + "<br/>");

Output: https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6jjQJJ0IkxE7s_2BEUyfOl_uBI_pCJKvsBlJ0QQMpAy3hv9Lxf6CVPWyDKNP20FEAtBnzooPtnMMgTjL841snOzNrcjg5JZDBOaAHDgPMPf2krf6FyPb5UVPEXG3Ez0GPyj8qKjydR4Hd/s1600/Date+Conversion+methods.png

DateTime format strings Response.Write("d - "
+ DateTime.Now.ToString("d") + "<br/>");
Response.Write(
"D - " + DateTime.Now.ToString("D") + "<br/>");
Response.Write(
"dd/MM/yyyy - " + DateTime.Now.ToString("dd/MM/yyyy") + "<br/>");
Response.Write(
"dd/MMMM/yyyy - " + DateTime.Now.ToString("dd/MMMM/yyyy") + "<br/>");
Response.Write(
"dd/MMMM/yy - " + DateTime.Now.ToString("dd/MMMM/yy") + "<br/>");
Response.Write(
"MM/dd/yy - " + DateTime.Now.ToString("MM/dd/yy") + "<br/>");

Output https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwn6eutD4S6aDlrFm-Hvm9wYe-kRBKTfMQTzeOt8HziFdY1uWlEP3AnGeNUlaD5Jy67_TaasjdlTfjN7ygkNVwKzD9tdjyENahofWAXfZsVtefNdVl8u_66PtG-lBGtnRqDQ7WgBtv8aBx/s1600/DateTime+format+strings.png
Asp.net calendar control properties and events

Useful Properties of the Calendar control Caption - This is a string read/write property.
CaptionAlign - Used to align the caption.
DayHeaderStyle - Style properties that can be used to customize the look and feel of the day header in the calendar
DayNameFormat - Can be Full, Short, FirstLetter, FirstTwoLetters, Shortest
DayStyle - Style properties that can be used to customize the look and feel of the day in the calendar
FirstDayOfWeek - Which day of the week is displayed first
NextPrevFormat - Can be ShortMonth, FullMonth, CustomText
NextMonthText - The text to use for the next month button.
PrevMonthText - The text to use for the previous month button.
SelectionMode - Can be Day, DayWeek, DayWeekMonth. Determines if Days, Weeks and Months are selectable.



If the SelectionMode is set to Day, then the user can select only one day. In this case to retrieve the selected date, we use SelectedDate property of the calendar as shown below.
Response.Write(Calendar1.SelectedDate.ToShortDateString());
However, if the SelectionMode is set to DayWeek or DayWeekMonth. In this case of you want to retrieve all the selected dates within the selected week or month, then SelectedDates property can be used as shown below. Using SelectedDate, property returns only the first selected date of the week or month.
foreach (DateTime selectedDate in Calendar1.SelectedDates)

{     Response.Write(selectedDate.ToShortDateString() + "<br/>");

}
Events: SelectionChanged - Fires when the date,week or Month selection is changed, by the user.
protected void Calendar1_SelectionChanged(object sender, EventArgs e)

{     foreach (DateTime selectedDate in Calendar1.SelectedDates)

    {         Response.Write(selectedDate.ToShortDateString() + "<br/>");

    } }



DayRender - Fires as a day in the calendar control is being rendered. protected void Calendar1_DayRender(
object sender, DayRenderEventArgs e)
{
   
if (!e.Day.IsOtherMonth && e.Day.Date.Day % 2 == 0)
    {
        e.Cell.Text =
"x";
        e.Cell.Font.Bold =
true;
        e.Cell.ForeColor = System.Drawing.
Color.White;
        e.Cell.BackColor = System.Drawing.
Color.Red;
        e.Cell.ToolTip =
"Booked";
    }
   
else
    {
        e.Cell.ToolTip =
"Available";
    }
}

VisibleMonthChanged - Fires when the visible month is changed by the user protected void
Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
{
    Response.Write(
"Month changed from ");
    Response.Write(GetMonthName(e.PreviousDate.Month));
    Response.Write(" to ");
    Response.Write(GetMonthName(e.NewDate.Month));
}
private string GetMonthName(int MonthNumber)
{
   
switch (MonthNumber)
    {
    case 1:
        return
"Jan";
    case 2:
        return
"Feb";
    case 3:
        return
"Mar";
    case 4:
        return
"Apr";
    case 5:
        return
"May";
    case 6:
        return
"Jun";
    case 7:
        return
"Jul";
    case 8:
        return
"Aug";
    case 9:
        return
"Sep";
    case 10:
        return
"Oct";
    case 11:
        return
"Nov";
    case 12:
        return
"Dec";
    default:
        return
"Invalid Month";
    }
}
Hidden field in asp.net

In this video we will learn about HiddenField in asp.net
The HiddenField control is used to store a value that needs to be persisted across posts to the server, but you don't want the control or it's value visible to the user. For example, when editing and updaing an employee record, we don't want the user to see the EmployeeId. So, we will store the EmployeeId in a HiddenField, so that it can then be used on the server to update the correct employees record.

SQL Script
Create Table tblEmployees
(
 Id
int Primary Key,
 Name nvarchar(50),
 Gender nvarchar(10),
 DeptName nvarchar(10)
)

Insert into tblEmployees values(201, 'Mark', 'Male', 'IT')
Insert into tblEmployees values(202, 'Steve', 'Male', 'Payroll')
Insert into tblEmployees values(203, 'John', 'Male', 'HR')



HTML of the ASPX Page <asp:HiddenField ID="HiddenField1" runat="server" />
<table>
    <tr>
        <td>Name:</td>
        <td>
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            </td>
    </tr>
    <tr>
        <td>Gender:</td>
        <td>
            <asp:TextBox ID="txtGender" runat="server"></asp:TextBox>
            </td>
    </tr>
    <tr>
        <td>Department:</td>
        <td>
            <asp:TextBox ID="txtDept" runat="server"></asp:TextBox>
            </td>
    </tr>
</table>
<asp:Button ID="Button1" runat="server" Text="Update Employee"
    onclick="Button1_Click" />&nbsp;
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
    Text="Load Employee" />



Code-Behind code:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        LoadEmployee();
    }
}

private void LoadEmployee()
{
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
   
using (SqlConnection con = new SqlConnection(CS))
    {
        string sqlQuery = "Select Id, Name, Gender, DeptName from tblEmployees where Id=202";
       
SqlCommand cmd = new SqlCommand(sqlQuery, con);
        con.Open();
       
using (SqlDataReader rdr = cmd.ExecuteReader())
        {
           
while (rdr.Read())
            {
                txtName.Text = rdr["Name"].ToString();
                txtGender.Text = rdr["Gender"].ToString();
                txtDept.Text = rdr["DeptName"].ToString();
                HiddenField1.Value = rdr["Id"].ToString();
            }
        }
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
    string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
   
using (SqlConnection con = new SqlConnection(CS))
    {
        string sqlQuery = "Update tblEmployees set Name=@Name, Gender=@Gender, DeptName=@DeptName where Id=@Id";
       
SqlCommand cmd = new SqlCommand(sqlQuery, con);
               
        cmd.Parameters.AddWithValue("@Name", txtName.Text);
        cmd.Parameters.AddWithValue("@Gender", txtGender.Text);
        cmd.Parameters.AddWithValue("@DeptName", txtDept.Text);
        cmd.Parameters.AddWithValue("@Id", HiddenField1.Value);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();

        txtName.Text = "";
        txtDept.Text = "";
        txtGender.Text = "";
    }
}

protected void Button2_Click(object sender, EventArgs e)
{
    LoadEmployee();
}

HiddenField: 1. Value property of the HiddenFiled is used to Get or set the value.
2. The value is stored as string
3. ViewState uses HiddenFiled to maintain state across postback
4. HiddenField is rendered as an <input type= "hidden"/> element

Alternatives for HiddenField: View state, QueryStrings, session state, and cookies can be used as an alternative for HiddenField. Session state and cookies will be accessible from other pages as well, and will be available untill their timeout has reached. Where as ViewState and HiddenField data, is available only on that page and the data is lost when you navigate away from the page.

Advantages of HiddenField: HiddenFiled data is lost when you navigate away from the page. Doesn't require any explicit cleanup task.
HiddenField is accessible to client-side scripts
<script type="text/javascript">     function GetHiddenFieldValue()      {         alert(document.getElementById('HiddenField1').value);     } </script>
Disadvantage of HiddenField: Hidden field data can be seen, by viewing the page source. Never, use HiddenFiled to store confidential data
Multiview control in asp.net

In this video we will discuss about the Multiview and View controls in asp.net. As the name states, a multiview is made up of multiple view controls, and each view control inturn can have controls inside it.
The HTML below shows a multiview, with 3 views <asp:MultiView ID="MultiView1" runat="server">
    <asp:View ID="View1" runat="server">
    </asp:View>  
    <asp:View ID="View2" runat="server">
    </asp:View>
    <asp:View ID="View3" runat="server">
    </asp:View>
</asp:MultiView>



Let's create a simple example, where we want to capture employee information on a step by step basis.
1. First capture Employee Personal details
2. Next capture Employee contact details
3. Show summary for confirmation. Upon confirmation, save the data to a database table

HTML of the aspx page <div style="font-family: Arial">
    <asp:MultiView ID="multiViewEmployee" runat="server">
        <asp:View ID="viewPersonalDetails" runat="server">
            <table style="border:1px solid black">
                <tr>
                    <td colspan="2">
                        <h2>Step 1 - Personal Details</h2>
                    </td>
                </tr>
                <tr>
                    <td>First Name</td>
                    <td>
                        <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Last Name</td>
                    <td>
                        <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Gender</td>
                    <td>
                        <asp:DropDownList ID="ddlGender" runat="server">
                            <asp:ListItem Text="Male" Value="Male"></asp:ListItem>
                            <asp:ListItem Text="Female" Value="Female"></asp:ListItem>
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" style="text-align:right">
                        <asp:Button ID="btnGoToStep2" runat="server"
                        Text="Step 2 >>" onclick="btnGoToStep2_Click" />
                    </td>
                </tr>
            </table>
        </asp:View>  
        <asp:View ID="viewContactDetails" runat="server">
            <table style="border:1px solid black">
                <tr>
                    <td colspan="2">
                        <h2>Step 2 - Contact Details</h2>
                    </td>
                </tr>
                <tr>
                    <td>Email Address</td>
                    <td>
                        <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Mobile Number</td>
                    <td>
                        <asp:TextBox ID="txtMobile" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="btnBackToStep1" runat="server" Text="<< Step 1"
                            onclick="btnBackToStep1_Click" />
                    </td>
                    <td style="text-align:right">
                        <asp:Button ID="btnGoToStep3" runat="server" Text="Step 3 >>"
                            onclick="btnGoToStep3_Click" />
                    </td>
                </tr>
            </table>
        </asp:View>
        <asp:View ID="viewSummary" runat="server">
            <table style="border:1px solid black">
                <tr>
                    <td colspan="2"><h2>Step 3 - Summary</h2></td>
                </tr>
                <tr>
                    <td colspan="2"><h3>Personal Details</h3></td>
                </tr>
                <tr>
                    <td>First Name</td>
                    <td>
                        :<asp:Label ID="lblFirstName" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td>Last Name</td>
                    <td>
                        :<asp:Label ID="lblLastName" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td>Gender</td>
                    <td>
                        :<asp:Label ID="lblGender" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td colspan="2"><h3>Contact Details</h3></td>
                </tr>
                <tr>
                    <td>Email Address</td>
                    <td>
                        :<asp:Label ID="lblEmail" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td>Mobile Number</td>
                    <td>
                        :<asp:Label ID="lblMobile" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="Button1" runat="server" Text="<< Step 2"
                            onclick="Button1_Click" />
                    </td>
                    <td style="text-align:right">
                        <asp:Button ID="Button2" runat="server" Text="Submit >>"
                            onclick="Button2_Click" />
                    </td>
                </tr>
            </table>
        </asp:View>
    </asp:MultiView>
</div>



Code-Behind Page: protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        multiViewEmployee.ActiveViewIndex = 0;
    }
}
       
protected void btnGoToStep2_Click(object sender, EventArgs e)
{
    multiViewEmployee.ActiveViewIndex = 1;
}

protected void btnBackToStep1_Click(object sender, EventArgs e)
{
    multiViewEmployee.ActiveViewIndex = 0;
}

protected void btnGoToStep3_Click(object sender, EventArgs e)
{
    lblFirstName.Text = txtFirstName.Text;
    lblLastName.Text = txtLastName.Text;
    lblGender.Text = ddlGender.SelectedValue;

    lblEmail.Text = txtEmail.Text;
    lblMobile.Text = txtMobile.Text;

    multiViewEmployee.ActiveViewIndex = 2;
}

protected void Button1_Click(object sender, EventArgs e)
{
    multiViewEmployee.ActiveViewIndex = 1;
}

protected void Button2_Click(object sender, EventArgs e)
{
   
// Write ado.net code to save data to a database table
     Response.Redirect("~/Confirmation.aspx");
}

ActiveViewIndex property of the Multiview control is used to determine, the view that is visible or active.

This can also be achieved using the wizard control. We will discuss about wizard control in the next video session.

Another way to achieve this, is by creating multiple webforms and passing data between webforms using
1. Cookies
2. Query Strings
3. Session variables

We will discuss about these different techniques and their advantages and disadvantages in a later video session.
Asp.net Wizard control properties

Properties: ActiveStepIndex - Used to set or get the ActiveStepIndex of the wizard control
DisplayCancelButton - Determines the visibility of the cancel button in the wizard control
CancelButtonImageUrl - If the cancel button type is set to Image button. Then set this property to specify the image.
CancelButtonStyle - The style properties to customize the cancel button
CancelButtonText - If the cancel button type is set to Link or Button, then set this property to specify the Text of the button.
CancelButtonType - Use to Specify the type of cancel button. This can be Button, Image or Link.
CancelDestinationPageUrl - The destination page to redirect to, when the cancel button is clicked. This can be a page with in the application or an external website.



DisplaySideBar - Determines if the wizard sidebar should be displayed or not
FinishCompleteButtonType - The button type of the finish step's finish button
FinishPreviousButtonType - The button type of the finish step's previous button
HeaderStyle - The style properties to customize the wizard header
HeaderText - The header text of the wizard control
protected void Page_PreRender(object sender, EventArgs e)

{     if (Wizard1.ActiveStepIndex == 1)

    {         Wizard1.HeaderText = "Contact Details";

    }     else if (Wizard1.ActiveStepIndex == 2)

    {         Wizard1.HeaderText = "Summary";

    } }



NavigationButtonStyle - The style properties to customize the wizard navigation buttons
NavigationStyle - The style properties to customize the navigation area that holds the navigation buttons
SideBarButtonStyle - The style properties to customize the wizard sidebar buttons
SideBarStyle - The style properties to customize the wizard sidebar
StartNextButtonType - The type of the start step's next button
StepNextButtonType - The button type of next step button
StepPreviousButtonType - The button type of previous step button
StepStyle - The style properties to customize the wizard steps

Note: WizardSteps can be added in the HTML source or using the WizardSteps collection editor.
Asp.net Wizard control events
Drag and drop a wizard control on the webform. Right click on the wizard control and select the properties. Click on the events icon. This displays all the events of the wizard control.

To generate the event handler method for ActiveStepChanged event, double click on the textbox next to the event. Follow the same process to generate the event handler methods for the rest of the events of the wizard control.



HTML of the aspx page: <div style="font-family: Arial">
    <asp:Wizard ID="Wizard1" runat="server"
        onactivestepchanged="Wizard1_ActiveStepChanged"
        oncancelbuttonclick="Wizard1_CancelButtonClick"
        onnextbuttonclick="Wizard1_NextButtonClick"
        onfinishbuttonclick="Wizard1_FinishButtonClick"
        onpreviousbuttonclick="Wizard1_PreviousButtonClick"
        onsidebarbuttonclick="Wizard1_SideBarButtonClick">
        <SideBarStyle VerticalAlign="Top" />
        <WizardSteps>
            <asp:WizardStep runat="server" title="Step 1">
                <asp:CheckBox ID="chkBoxCancel" Text="Cancel Navigation" runat="server" />
            </asp:WizardStep>
            <asp:WizardStep runat="server" title="Step 2">
            </asp:WizardStep>
            <asp:WizardStep runat="server" title="Step 3">
            </asp:WizardStep>
        </WizardSteps>
    </asp:Wizard>
</div>



Code-Behind page code:
// ActiveStepChanged - Fires when the active step of the index is changed.
protected void
Wizard1_ActiveStepChanged(object sender, EventArgs e)
{
    Response.Write(
"Active Step Changed to " + Wizard1.ActiveStepIndex.ToString() + "<br/>");
}
// CancelButtonClick - Fires when the cancel button of the wizard control is clicked.
// To display the cancel button, set DisplayCancelButton=True.
protected void
Wizard1_CancelButtonClick(object sender, EventArgs e)
{
    Response.Redirect(
"Cancel Button Clicked");
}
// NextButtonClick - Fires when the next button of the wizard control is clicked.
protected void
Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
{
    Response.Write(
"Current Step Index = " + e.CurrentStepIndex.ToString() + "<br/>");
    Response.Write(
"Next Step Index = " + e.NextStepIndex.ToString() + "<br/>");
   
if (chkBoxCancel.Checked)
    {
        Response.Write(
"Navigation to next step will be cancelled");
        e.Cancel =
true;
    }
}
// FinishButtonClick - Fires when the finish button is clicked
protected void
Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
    Response.Write(
"Finish button clicked <br/>");
    Response.Write(
"Current Step Index = " + e.CurrentStepIndex.ToString() + "<br/>");
    Response.Write(
"Next Step Index = " + e.NextStepIndex.ToString());
}
// PreviousButtonClick - Fires when the previous button is clicked
protected void
Wizard1_PreviousButtonClick(object sender, WizardNavigationEventArgs e)
{
    Response.Write(
"Previous button clicked<br/>");
}
// SideBarButtonClick - Fires when the sidebar button is clicked
protected void Wizard1_SideBarButtonClick(object
sender, WizardNavigationEventArgs e)
{
    Response.Write(
"Sidebar button clicked<br/>");
}
UseSubmitBehavior property of the Button control

In this video we will discuss about the UseSubmitBehavior property of the asp.net Button control. Let us understand the use of this property with an example.

Design a webform with a TextBox, Label and 2 Button controls as shown in the image below.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRQvPY3H_fbgZMHUW6rXKs2ZzynnFMwtsw7o9kG__Y5F9_UVitb5qfP70v4U9I5BPSFqzwm7c02MFdxFLyRuNFMjV6aqENj3oqZsduS3lGr64Vs9TgdiVp9E_7Zd-HJJ9-ik0_OVF4yHN3/s1600/UseSubmitBehavior+property+example.png



For your convinience, I have included the HTML of the aspx page. <div style="font-family: Arial">
    <strong>Name : </strong>
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    <br />
    <br />
    <asp:Button ID="btnClear" runat="server" onclick="btnClear_Click" Text="Clear"/>
    &nbsp;
    <asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click" Text="Submit" />
    <br />
    <br />
    <asp:Label ID="lblMessage" runat="server" Font-Bold="True" ForeColor="#009933"></asp:Label>
</div>



Dobule click the Clear and Submit buttons, to generate the event handlers, and paste the following code in the code behind page.
protected void btnSubmit_Click(object sender, EventArgs e)
{
    lblMessage.Text = "You enetered: " + txtName.Text;
}

protected void btnClear_Click(object sender, EventArgs e)
{
    txtName.Text = "";
}

Now, run the web application project. Enter a name in the textbox and hit the enter key on the keyboard. Notice that the cancel button has the submit behaviour.

In the HTML of the aspx page, set UseSubmitBehavior="false" for the clear button. <asp:Button ID="btnClear" UseSubmitBehavior="false" runat="server"
onclick="btnClear_Click" Text="Clear"/>

Now, run the web application project again. Enter a name in the textbox and hit the enter key on the keyboard. Notice that the submit button has the submit behaviour, as expected.

The UseSubmitBehavior property specifies if the Button control uses the browser's built-in submit function or the ASP.NET postback mechanism.

This property is TRUE by default. When set to FALSE, ASP.NET adds a client-side script to post the form. To view the client side script added by the ASP.NET, right click on the broswer and view source.
Asp.net wizard control templates

we will look at the advanced features of the wizard control like
1. Set focus to the first control in the wizard step when the page loads, so that the user can start typing into the textbox directly.
2. Attach javascript to the Next, Previous and Finish buttons, to display a confirmation dialog box before the user moves to the next step.
3. Setting UseSubmitBehavior="true" for the Previous button in the wizard control.



In the HTML below, we have a wizard control with 3 steps. Each step has a TextBox control.  <asp:Wizard ID="Wizard1" runat="server">
    <WizardSteps>
        <asp:WizardStep ID="WizardStep1" runat="server" Title="Step 1">
            <asp:TextBox ID="Step1TextBox" runat="server"></asp:TextBox>
        </asp:WizardStep>
        <asp:WizardStep ID="WizardStep2" runat="server" Title="Step 2">
            <asp:TextBox ID="Step2TextBox" runat="server"></asp:TextBox>
        </asp:WizardStep>
        <asp:WizardStep ID="WizardStep3" runat="server" Title="Step 3">
            <asp:TextBox ID="Step3TextBox" runat="server"></asp:TextBox>
        </asp:WizardStep>
    </WizardSteps>
</asp:Wizard>



The following code, sets the focus to the correct textbox, based on the ActiveStepIndex. Make sure you have this code in the Page_PreRender event. Copying this code in the Page_Load() event will not work correctly. This is because the ActiveStepIndex is changed on the Button click event which happens after the Page_Load() event. As the Page_PreRender() events occurs after the Button_Click event, the code works correctly as expected.
protected void Page_PreRender(
object sender, EventArgs e)
{
    if (Wizard1.ActiveStepIndex == 0)
    {
        Step1TextBox.Focus();
    }
    else if (Wizard1.ActiveStepIndex == 1)
    {
        Step2TextBox.Focus();
    }
    else if (Wizard1.ActiveStepIndex == 2)
    {
        Step3TextBox.Focus();
    }
}

To attach, javascript to the buttons in the navigation bar(next, previous, Finish), we need to use Navigation Templates. By default, the wizard control generates these buttons automatically. To make the wizard control use navigation templates and attach javascript
1. Right click on the wizard control and select "Show smart tag"
2. Click on "Convert To Start Navigation Template".
3. Now in the HTML source, specify the javascript that needs to be executed in response to the OnClientClick event.
<asp:Wizard ID="Wizard1" runat="server">
    <StartNavigationTemplate>
        <asp:Button ID="StartNextButton" runat="server" CommandName="MoveNext" Text="Next"
            OnClientClick="return confirm('Are you sure you want to go to next step');" />
    </StartNavigationTemplate>
    <WizardSteps>
        <asp:WizardStep ID="WizardStep1" runat="server" Title="Step 1">
            <asp:TextBox ID="Step1TextBox" runat="server"></asp:TextBox>
        </asp:WizardStep>
        <asp:WizardStep ID="WizardStep2" runat="server" Title="Step 2">
            <asp:TextBox ID="Step2TextBox" runat="server"></asp:TextBox>
        </asp:WizardStep>
        <asp:WizardStep ID="WizardStep3" runat="server" Title="Step 3">
            <asp:TextBox ID="Step3TextBox" runat="server"></asp:TextBox>
        </asp:WizardStep>
    </WizardSteps>
</asp:Wizard>

Use StepNavigationTemplate, to attach javascript to the Next and Previous buttons on all wizard steps, where StepType="Step"
Use FinishNavigationTemplate, to attach javascript to the Finish button on the last step of the wizard control.

It is also possible to add javascript in code. To add the javascript using code for the Next button, in a wizard step, where StepType="Step"
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Button btnNext = (
Button)Wizard1.FindControl("StepNavigationTemplateContainerID").FindControl("StepNextButton");
        btnNext.Attributes.Add(
"onclick", "return confirm('Are you sure you want to move to the next step');");
    }
}

To make the next button of the wizard control the default button, set UseSubmitBehavior=False for the Previous button. So that, when the user hits the Enter key, after entering the required data, the user moves to the next step and not the previous step
 


we will discuss about the Literal control. In my opinion this is the least understood control in asp.net.

Topics Discussed a) Literal control in asp.net
b) Difference between a literal control and label control



1. In many ways a Literal control is similar to a Label control. Both of these controls are used to display Text on a webform. The Text property can be set in the HTML or in the code-behind.

2. Label control wraps the text in a span tag when rendered. Any style that is applied to the Label control, will be rendered using the style property of the span tag.

For example, the following HTML <asp:Label ID="Label1" runat="server"  Text="Lable Text"
ForeColor="Red" Font-Bold="true" ></asp:Label>

Will be rendered as <span id="Label1" style="color:Red;font-weight:bold;">Lable Text</span>



3. A literal control, doesn't output any surrounding tags. The Text is displayed as is.
For example, the following HTML
<asp:Literal ID="Literal1" runat="server"
Text="Literal Control Text"></asp:Literal>

will be rendered as Literal Control Text

4. If you want to apply any styles to a literal control, include them in the Text of the literal control. For example, the following HTML sets the font to red color and bold. <asp:Literal ID="Literal1" runat="server"
Text="<b><font color='Red'>Literal Control Text</font></b>">
</asp:Literal>

The above HTML will be rendered as <b><font color='Red'>Literal Control Text</font></b>

5. So, if you just want the text to be displayed without any styles, then use Literal control, else use Label control.

6. By default, both the Label and Literal Control's does not encode the text they display. For example, the following HTML displays a javascript alert  <asp:Label ID="Label" runat="server"
Text="<script>alert('Lable Text');</script>">
</asp:Label>
<br />
<asp:Literal ID="Literal1" runat="server"
Text="<script>alert('Literal Text');</script>">
</asp:Literal>

and will be rendered as <span id="Label"><script>alert('Lable Text');</script></span>
<br />
<script>alert('Literal Text');</script>

7. To HTML encode the Label Text, Server.HtmlEncode() method can be used, and for Literal control, Mode property can be used.
<asp:Label ID="Label1" runat="server">
<%=Server.HtmlEncode("<script>alert('Lable Text');</script>")%>
</asp:Label>
<br />
<asp:Literal ID="Literal1" runat="server"
Text="<script>alert('Literal Text');</script>"
Mode="Encode"></asp:Literal>

The above HTML will be rendered as <span id="Label1">&lt;script&gt;alert(&#39;Lable Text&#39;);&lt;/script&gt;</span>
<br />
&lt;script&gt;alert(&#39;Literal Text&#39;);&lt;/script&gt;

8. Literal control is a light weight control, when compared with the Label control.

9. The inheritance hierarchy for Literal control class is (Object => Control => Literal), where as for the Lable control, the hierarchy is (Object => Control => WebControl=> Label)

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgvz8aS4R7cZuP_-xrol6VM3A3czbK4Reooqyxc1g_PhBV8vqMhnZQ9jA_J0TKepYeuE4TDACdSO7HYq0o4eHMhBQ_ZWrSru-zrs8SjtBoDI03O49w8DOPJPNr4pXoZVGSyhR7O8a3Jy-37/s1600/Difference+between+Label+and+Literal+controls+in+asp.net.png
The panel control is used as a container for other controls. A panel control is very handy, when you want to group controls, and then show or hide, all the controls in the group. Panel control, is also very useful, when adding controls to the webform dynamically. We will discuss about, adding controls dynamically using panel control in the next video session.

In this video, we will discuss about, using the Panel control to group controls, and then toggle their visibility, using the Panel control's Visible property.

The following webform is used by both, an Admin and Non-Admin user. When the Admin user is selected from the dropdownlist, we want to show the controls that are relevant to the Admin user. When the Non-Admin user is selected, only the Non-Admin specific content and controls should be shown.



HTML of the ASPX page. At the moment we are not using Panel control. <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
            onselectedindexchanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem Text="Select User" Value="-1"></asp:ListItem>
    <asp:ListItem Text="Admin" Value="Admin"></asp:ListItem>
    <asp:ListItem Text="Non-Admin" Value="Non-Admin"></asp:ListItem>
</asp:DropDownList>
<table>
    <tr>
        <td colspan="2">
            <asp:Label ID="AdminGreeting" runat="server" Font-Size="XX-Large"
            Text="You are logged in as an administrator">
            </asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="AdminNameLabel" runat="server" Text="Admin Name:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="AdminNameTextBox" runat="server" Text="Tom">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="AdminRegionLabel" runat="server" Text="Admin Region:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="AdminRegionTextBox" runat="server" Text="Asia">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="AdminActionsLabel" runat="server" Text="Actions:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="AdminActionsTextBox" runat="server" Font-Size="Medium" TextMode="MultiLine"
               
                Text="There are 4 user queries to be answered by the end of Dcemeber 25th 2013."
                Font-Bold="True" ></asp:TextBox>
        </td>
    </tr>
</table>
<table>
    <tr>
        <td colspan="2">
            <asp:Label ID="NonAdminGreeting" runat="server" Font-Size="XX-Large"
            Text="Welcome Tom!">
            </asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="NonAdminNameLabel" runat="server" Text="User Name:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="NonAdminNameTextBox" runat="server" Text="Mike">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="NonAdminRegionLabel" runat="server" Text="User Region:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="NonAdminRegionTextBox" runat="server" Text="United Kingdom">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="NonAdminCityLabel" runat="server" Text="City:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="NonAdminCityTextBox" runat="server" Text="London">
            </asp:TextBox>
        </td>
    </tr>
</table>



Code-Behind code. Since we are not using the panel control, each control's visible property need to be changed depending on the selection in the dropdownlist. protected void
Page_Load(object sender, EventArgs e)
{
   
// When the page first loads, hide all admin and non admin controls
   
if (!IsPostBack)
    {
        HideAdminControls();
        HideNonAdminControls();
    }
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
   
if (DropDownList1.SelectedValue == "Admin")
    {
        ShowAdminControls();
        HideNonAdminControls();
    }
   
else if (DropDownList1.SelectedValue == "Non-Admin")
    {
        ShowNonAdminControls();
        HideAdminControls();
    }
   
else
    {
        HideAdminControls();
        HideNonAdminControls();
    }
}

private void HideAdminControls()
{
    AdminGreeting.Visible =
false;
    AdminNameLabel.Visible = 
false;
    AdminNameTextBox.Visible = 
false;
    AdminRegionLabel.Visible = 
false;
    AdminRegionTextBox.Visible = 
false;
    AdminActionsLabel.Visible = 
false;
    AdminActionsTextBox.Visible = 
false;
}
private void ShowAdminControls()
{
    AdminGreeting.Visible =
true;
    AdminNameLabel.Visible = 
true;
    AdminNameTextBox.Visible = 
true;
    AdminRegionLabel.Visible = 
true;
    AdminRegionTextBox.Visible = 
true;
    AdminActionsLabel.Visible = 
true;
    AdminActionsTextBox.Visible = 
true;
}
private void HideNonAdminControls()
{
    NonAdminGreeting.Visible = 
false;
    NonAdminNameLabel.Visible = 
false;
    NonAdminNameTextBox.Visible = 
false;
    NonAdminRegionLabel.Visible = 
false;
    NonAdminRegionTextBox.Visible = 
false;
    NonAdminCityLabel.Visible = 
false;
    NonAdminCityTextBox.Visible = 
false;
}
private void ShowNonAdminControls()
{
    NonAdminGreeting.Visible = 
true;
    NonAdminNameLabel.Visible = 
true;
    NonAdminNameTextBox.Visible = 
true;
    NonAdminRegionLabel.Visible = 
true;
    NonAdminRegionTextBox.Visible = 
true;
    NonAdminCityLabel.Visible = 
true;
    NonAdminCityTextBox.Visible = 
true;
}

HTML of the ASPX page. The panel control is used to group the controls. <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
            onselectedindexchanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem Text="Select User" Value="-1"></asp:ListItem>
    <asp:ListItem Text="Admin" Value="Admin"></asp:ListItem>
    <asp:ListItem Text="Non-Admin" Value="Non-Admin"></asp:ListItem>
</asp:DropDownList>
<asp:Panel ID="AdminPanel" runat="server">
<table>
    <tr>
        <td colspan="2">
            <asp:Label ID="AdminGreeting" runat="server" Font-Size="XX-Large"
            Text="You are logged in as an administrator">
            </asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="AdminNameLabel" runat="server" Text="Admin Name:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="AdminNameTextBox" runat="server" Text="Tom">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="AdminRegionLabel" runat="server" Text="Admin Region:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="AdminRegionTextBox" runat="server" Text="Asia">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="AdminActionsLabel" runat="server" Text="Actions:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="AdminActionsTextBox" runat="server" Font-Size="Medium" TextMode="MultiLine"
               
                Text="There are 4 user queries to be answered by the end of Dcemeber 25th 2013."
                Font-Bold="True" ></asp:TextBox>
        </td>
    </tr>
</table>
</asp:Panel>
<asp:Panel ID="NonAdminPanel" runat="server">
<table>
    <tr>
        <td colspan="2">
            <asp:Label ID="NonAdminGreeting" runat="server" Font-Size="XX-Large"
            Text="Welcome Tom!">
            </asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="NonAdminNameLabel" runat="server" Text="User Name:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="NonAdminNameTextBox" runat="server" Text="Mike">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="NonAdminRegionLabel" runat="server" Text="User Region:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="NonAdminRegionTextBox" runat="server" Text="United Kingdom">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="NonAdminCityLabel" runat="server" Text="City:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="NonAdminCityTextBox" runat="server" Text="London">
            </asp:TextBox>
        </td>
    </tr>
</table>
</asp:Panel>

Code-Behind code:  protected void Page_Load(
object sender, EventArgs e)
{
   
// When the page first loads, hide admin and non admin panels
   
if (!IsPostBack)
    {
        AdminPanel.Visible =
false;
        NonAdminPanel.Visible =
false;
    }
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
   
if (DropDownList1.SelectedValue == "Admin")
    {
        AdminPanel.Visible =
true;
        NonAdminPanel.Visible =
false;
    }
   
else if (DropDownList1.SelectedValue == "Non-Admin")
    {
        AdminPanel.Visible =
false;
        NonAdminPanel.Visible =
true;
    }
   
else
    {
        AdminPanel.Visible =
false;
        NonAdminPanel.Visible =
false;
    }
}

The panel control is used as a container for other controls. A panel control is very handy, when you want to group controls, and then show or hide, all the controls in the group. We have seen how to do this in Part 42, of this video series.

Panel control, is also very useful, when adding controls to the webform dynamically. We will discuss this in this session.



https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9ehTMpELJ2fd1qQ2ey7GLHhu5FPI_9Xk09ILGtBuBxXPU9bK45lzaUVJp6L78QFz8jXfviw5fW1NcpThgYbIFOYwm4PeBe6m6_CCP6LLbQNUNBdZwKKe7jMk4OBZr2_izheUTqhH2knmb/s1600/Generating+controls+dynamically+using+panel+control.png



HTML of the ASPX page
<div style="font-family: Arial">
    <table>
    <tr>
        <td><b>Control Type</b></td>
        <td>
            <asp:CheckBoxList ID="chkBoxListControlType" runat="server" RepeatDirection="Horizontal">
                <asp:ListItem Text="Label" Value="Label"></asp:ListItem>
                <asp:ListItem Text="TextBox" Value="TextBox"></asp:ListItem>
                <asp:ListItem Text="Button" Value="Button"></asp:ListItem>
            </asp:CheckBoxList>
        </td>
        <td><b>How Many</b></td>
        <td>
            <asp:TextBox ID="txtControlsCount" runat="server" Width="40px"></asp:TextBox>
        </td>
        <td>
            <asp:Button ID="btnGenerateControl" runat="server" Text="Generate Controls"
                onclick="btnGenerateControl_Click" />
        </td>
    </tr>
    <tr>
        <td colspan="5">
            <h3>Label Controls</h3>
        </td>
    </tr>
    <tr>
        <td colspan="5" id="tdLabels" runat="server">
            <asp:Panel ID="pnlLabels" runat="server">
            </asp:Panel>
            <%--<asp:PlaceHolder ID="phLabels" runat="server">
            </asp:PlaceHolder>--%>
        </td>
    </tr>
    <tr>
        <td colspan="5">
            <h3>TextBox Controls</h3>
        </td>
    </tr>
    <tr>
        <td colspan="5" id="tdTextBoxes" runat="server">
            <asp:Panel ID="pnlTextBoxes" runat="server">
            </asp:Panel>
            <%--<asp:PlaceHolder ID="phTextBoxes" runat="server">
            </asp:PlaceHolder>--%>
        </td>
    </tr>
    <tr>
        <td colspan="5">
            <h3>Button Controls</h3>
        </td>
    </tr>
    <tr>
        <td colspan="5" id="tdButtons" runat="server">
            <asp:Panel ID="pnlButtons" runat="server">
            </asp:Panel>
            <%--<asp:PlaceHolder ID="phButtons" runat="server">
            </asp:PlaceHolder>--%>
        </td>
    </tr>
    </table>      
</div>

Code-Behind Code:
protected void
btnGenerateControl_Click(object sender, EventArgs e)
{
   
// Retrieve the count of the controls to generate
    int
Count = Convert.ToInt16(txtControlsCount.Text);
   
// Loop thru each list item in the CheckBoxList
    foreach
(ListItem li in chkBoxListControlType.Items)
    {
       
if (li.Selected)
        {
           
// Generate Lable Controls
            if
(li.Value == "Label")
            {
               
for (int i = 1; i <= Count; i++)
                {
                   
Label lbl = new Label();
                    lbl.Text =
"Label - " + i.ToString();
                   
//phLabels.Controls.Add(lbl);
                    //tdLabels.Controls.Add(lbl);
                    pnlLabels.Controls.Add(lbl);
                }
            }
           
// Generate TextBox controls
            else if
(li.Value == "TextBox")
            {
               
for (int i = 1; i <= Count; i++)
                {
                   
TextBox txtBox = new TextBox();
                    txtBox.Text =
"TextBox - " + i.ToString();
                   
//phTextBoxes.Controls.Add(txtBox);
                    //tdTextBoxes.Controls.Add(txtBox);
                    pnlTextBoxes.Controls.Add(txtBox);
                }
            }
           
// Generate Button Controls
           
else
            {
               
for (int i = 1; i <= Count; i++)
                {
                   
Button btn = new Button();
                    btn.Text =
"Button - " + i.ToString();
                   
//phButtons.Controls.Add(btn);
                    //tdButtons.Controls.Add(btn);
                    pnlButtons.Controls.Add(btn);
                }
            }
        }
    }
}

Suggested Videos
Part 41 - Literal control in asp.net
Part 42 - Asp.net panel control
Part 43 - Creating controls dynamically using asp.net panel control

Validation controls are used to ensure if, the data, entered by the user is valid. Microsoft asp.net framework, provides 6 built-in validation controls.
1. RequiredFieldValidator
2. RangeValidator
3. RegularExpressionValidator
4. CompareValidator
5. CustomValidator  
6. ValidationSummary

RequiredField validator control in asp.net



These validation controls can be used to perform both client side and server side validation.

Browser's understand only client scripts and HTML. In the past to perform client side validation, developers had to write themselves the required javascript code. With validation controls, we don't have to write javascript, we can use the built-in validation controls, which will generate the required javascript for us.

Client scripts can spread viruses and cause security concerns. Because of this, users may disable JavaScript on their browser. If this happens, client side validation is skipped. That is why, it is always a good practice to have server side validation as well.

The validation control's also perform server side validation. Server side validation is always performed, irrespective of whether the client side validation is done or not.

In this video we will discuss about RequiredField validator control. This control, ensures that the required field is entered by the user. Let us understand with an example.



RequiredField validator control in asp.net

Consider the HTML below. TextBox with ID="txtName" expects the user to enter their name. This is required field. Next to this textbox is a RequiredFieldValidator control, which is used to ensure that the user has entered his name. ControlToValidate property specifies the control to validate. ErrorMessage is the message that is displayed when the validation fails. To validate ddlGender DropDownList, we have RequiredFieldValidatorGender. We have specified InitialValue="-1". This will ensure that, if the user has selected, "Select Gender" option from the DropDownList, the control will still fail the validation.
<table>
    <tr>
        <td>
            <b>Name</b>
        </td>
        <td>
            :<asp:TextBox ID="txtName" runat="server" Width="150px">
            </asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorName" runat="server"
            ErrorMessage="Name is required" ForeColor="Red"
            ControlToValidate="txtName" Display="Dynamic" >
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            <b>Gender</b>
        </td>
        <td>
            :<asp:DropDownList ID="ddlGender" runat="server" Width="150px">
                <asp:ListItem Text="Select Gender" Value="-1"></asp:ListItem>
                <asp:ListItem Text="Male" Value="Male"></asp:ListItem>
                <asp:ListItem Text="Female" Value="Female"></asp:ListItem>
            </asp:DropDownList>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorGender" runat="server"
            ErrorMessage="Gender is required" ForeColor="Red" InitialValue="-1"
            ControlToValidate="ddlGender" Display="Dynamic" >
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Button ID="btnSave" runat="server" Text="Save" Width="100px"
                onclick="btnSave_Click"/>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblStatus" runat="server" Font-Bold="true">
            </asp:Label>
        </td>
    </tr>
</table>

Code-Behind code: Page.IsValid is a read-only property. This property returns true if all the validation controls has passed validation. Use this property to perform server side validation.
protected void btnSave_Click(object sender, EventArgs e)
{
           
   
if (Page.IsValid)
    {
        lblStatus.ForeColor = System.Drawing.
Color.Green;
        lblStatus.Text =
"Data saved successfully!";
    }
    else
    {
        lblStatus.ForeColor = System.Drawing.
Color.Red;
        lblStatus.Text =
"Data not valid and not saved!";
    }
}

Run the project, and notice that the client side validation is performed. Now, disable Javascript. To disable javascript in, internet explorer
1. Click on Tools on the Menu Bar. If the Menu bar is not visible, press ALT+T.
2. From the Tools menu, select Internet Options
3. Click on the Security tab, on the internet options window
4. Select Local Intranet icon and click on Cutom Level button
5. Scroll down in the Security Settings window, and find Scripting option in the list.
6. Click Disable radiobutton under active scripting
7. Click OK and click Yes on the warning.

The above steps should disable javascript. Run the project now, and click Save button, without entering any data. Notice, that the client side validation is skipped, but the server side validation is performed.

Rangevalidator control in asp.net - Part 45
Suggested Videos Part 42 - Asp.net panel control
Part 43 - Creating controls dynamically using asp.net panel control
Part 44 - RequiredField validator control in asp.net

In this video we will discuss about Rangevalidator control. This control is used to check if the value is within a specified range of values. For example, Rangevalidator can be used to check if the age falls between 1 and 100.

RangeValidator control in asp.net

In the HTML below, TextBox txtAge captures age of the person. If the user enter's any number that is not between 1 & 100 the validation fails. The minimum and maximum value for the age is specified by MinimumValue and MaximumValue properties. Since, age is an integer, the Type is specified as integer.
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
    ErrorMessage="Age must be between 1 & 100"
    MinimumValue="1" MaximumValue="100"
    ControlToValidate="txtAge" Type="Integer" >
</asp:RangeValidator>



Properties specific to Rangevalidator control: Type - This property, specifies the data type of the value to check. Data types supported include - Currency, Date, Double, Integer, String.
MinimumValue - The minimum value allowed
MaximumValue - The maximum value allowed

Comple HTML of the aspx page used in the Demo: Rangevalidator only checks if the entered data is within the allowed range. If you want to check for a required field, use RequiredFieldValidator. For the age field, we are using both RequiredFieldValidator and RangeValidator. Also notice that, in this example we are using the Display property. If the Display property is not set, or, if it is set to static, then the error message will be rendered, with style visibility:hidden. Because of this, the error message will always occupy the space on the screen even if the validation passes. This pushes "Age is Required" error message to the right. To correct this we have set Display="Dynamic". This renders the error message with style display:none. If a tag has this style, it will not occupy space when not visible.
<table>
    <tr>
        <td>
            <b>Age</b>
        </td>
        <td>
            :<asp:TextBox ID="txtAge" runat="server" Width="150px">
                </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorAge" runat="server"
                ErrorMessage="Age must be between 1 & 100"
                MinimumValue="1" MaximumValue="100"
                ControlToValidate="txtAge" Type="Integer"
                ForeColor="Red" Display="Dynamic">
            </asp:RangeValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorAge"
            runat="server" ErrorMessage="Age is required"
            ControlToValidate="txtAge" ForeColor="Red"
            Display="Dynamic" >
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            <b>Date Available</b>
        </td>
        <td>
            :<asp:TextBox ID="txtDateAvailable" runat="server" Width="150px">
            </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorDateAvailable" runat="server"
                ErrorMessage="Date must be between 01/01/2012 & 31/12/2012"
                MinimumValue="01/01/2012" MaximumValue="31/12/2012"
                ControlToValidate="txtDateAvailable" Type="Date"
                ForeColor="Red">
            </asp:RangeValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Button ID="btnSave" runat="server" Text="Save" Width="100px"
                onclick="btnSave_Click" />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblStatus" runat="server" Font-Bold="true">
            </asp:Label>
        </td>
    </tr>
</table>



Code-Behind page code: protected void
btnSave_Click(object sender, EventArgs e)
{
   
if (Page.IsValid)
    {
        lblStatus.ForeColor = System.Drawing.
Color.Green;
        lblStatus.Text =
"Data Saved successfully";
    }
   
else
    {
        lblStatus.ForeColor = System.Drawing.
Color.Red;
        lblStatus.Text =
"Validation Failed! Data not saved";
    }
}

Display property is supported by all validation controls. None - Error message not rendered and displayed next to the control. Used to show the error message only in the ValidationSummary control
Static - The error message is displayed next to the control if validation fails. Space is reserved on the page for the message even if validation succeeds. The span tag is rendered with style visibility:hidden
Dynamic - The error message is displayed next to the control if validation fails. Space is not reserved on the page for the message if the validation succeeds. The span tag is rendered with style display:none.
CompareValidator control in asp.net
CompareValidator control is used to compare the value of one control with the value of another control or a constant value. The comparison operation can be any of the following. 1. Equal
2. GreaterThan
3. GreaterThanEqual
4. LessThan
5. LessThanEqual
6. NotEqual
7. DataTypeCheck

CompareValidator control in asp.net



CompareValidator can also be used for DataType checking.
The following are the properties that are specific to the compare validator 1. ControlToCompare - The control with which to compare
2. Type - The DataType of the value to compare. String, Integer etc.
3. Operator = The comparison operator. Equal, NotEqual etc.
4. ValueToCompare - The constant value to compare with.

SetFocusOnError property is supported by all validation controls. If this property is set to true, then the control will automatically receive focus, when the validation fails.



Using CompareValidator to compare the value of one control with the value of another control. <table>
    <tr>
        <td>
            <b>Password</b>
        </td>
        <td>
            :<asp:TextBox ID="txtPassword" runat="server" Width="150px" TextMode="Password"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <strong>Retype Password</strong></td>
        <td>
            :<asp:TextBox ID="txtRetypePassword" runat="server"
                Width="150px" TextMode="Password"></asp:TextBox>
            <asp:CompareValidator ID="CompareValidatorPassword" runat="server"
            ErrorMessage="Password and Retype Password must match"
            ControlToValidate="txtRetypePassword" ControlToCompare="txtPassword"
            Type="String" Operator="Equal" ForeColor="Red">
            </asp:CompareValidator>
        </td>
    </tr>
</table>

Using CompareValidator to compare the value of one control with a constant value. <asp:TextBox ID="txtDateofapplication" runat="server" Width="150px">
</asp:TextBox>
<asp:CompareValidator ID="CompareValidatorDateofbirth" runat="server"
ErrorMessage="Date of application must be greater than 01/01/2012"
ControlToValidate="txtDateofapplication" ValueToCompare="01/01/2012"
Type="Date" Operator="GreaterThan" ForeColor="Red"
SetFocusOnError="true"></asp:CompareValidator>

Using CompareValidator to check DataType <asp:TextBox ID="txtAge" runat="server" Width="150px"></asp:TextBox>
<asp:CompareValidator ID="CompareValidatorAge" runat="server"
ErrorMessage="Age must be a number" ControlToValidate="txtAge"
Operator="DataTypeCheck" Type="Integer" ForeColor="Red"
SetFocusOnError="true"></asp:CompareValidator>
RegularExpressionValidator control in asp.net

This is a very powerful validation control. This control is used to check if the value of an associated input control matches the pattern specified by a regular expression. The only property that is specific to the RegularExpressionValidator is ValidationExpression.

RegularExpressionValidator control in asp.net



This example, checks if the input mataches the pattern of an email address <asp:TextBox ID="txtEmail" runat="server" Width="150px">
</asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail" runat="server"
ControlToValidate="txtEmail" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
ErrorMessage="Invalid Email" ForeColor="Red"></asp:RegularExpressionValidator>



By default client side validation is turned on. To disable client side validation set EnableClientScript o false. This property is supported by all validation controls.

To disable validation control set Enabled propety to false.
CustomValidator control in asp.net
CustomValidator control in asp.net

CustomValidator control allows us to write a method with a custom logic to handle the validation of the value entered. If none of the other validation controls, serve our purpose, then the CustomValidator can be used.



Just like any other validation control, CustomValidator can be used for both client and server side validation. Client side and server side validation functions, needs to be written by the developer, and associate them to the custom validator control.

The following are the properties that are specific to the CustomValidator control ClientValidationFunction - Specifies the name of the client side validation method.
ValidateEmptyText - Specifies whether the validator validates the control, when the text of the control is empty. By default this property is false, and both the client side and server side validation functions will not be invoked, if the associated input control is empty.

Events specific to the CustomValidator control OnServerValidate - Specifies the name of the server side validation method.



HTML of the aspx page: This example checks if the entered number is even. ValidateEmptyText property of the CustomValidator control, is set to true. So the validation is also triggered when the textbox is empty.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script language="javascript" type="text/javascript">
        // Client side validation function to check if the number is even.
        function IsEven(source, args)
        {
            if (args.Value == "")
            {
                args.IsValid = false;
            }
            else
            {
                if (args.Value % 2 == 0)
                {
                    args.IsValid = true;
                }
                else
                {
                    args.IsValid = false;
                }
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="font-family: Arial">
        <table>
            <tr>
                <td>
                    <b>Please enter a positive even number</b>
                </td>
                <td>
                    <asp:TextBox ID="txtEvenNumber" runat="server"></asp:TextBox>
                    <asp:CustomValidator ID="CustomValidatorEvenNumber" runat="server"
                        ForeColor="Red"
                        ErrorMessage="Not an even number"
                        OnServerValidate="CustomValidatorEvenNumber_ServerValidate"
                        ControlToValidate="txtEvenNumber"
                        ClientValidationFunction="IsEven"
                        ValidateEmptyText="true">
                    </asp:CustomValidator>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Button ID="btnSubmit" runat="server" Text="Save"
                        onclick="btnSubmit_Click" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Label ID="lblStatus" runat="server" Font-Bold="true"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Code-Behind page code: Set EnableClientScript to true, to test the server side validation method.
protected void btnSubmit_Click(
object sender, EventArgs e)
{
   
if (Page.IsValid)
    {
        lblStatus.Text =
"Data Saved";
        lblStatus.ForeColor = System.Drawing.
Color.Green;
    }
   
else
    {
        lblStatus.Text =
"Validation Error! Data Not Saved";
        lblStatus.ForeColor = System.Drawing.
Color.Red;
    }
}

protected void CustomValidatorEvenNumber_ServerValidate(object source, ServerValidateEventArgs args)
{
   
if (args.Value == "")
    {
        args.IsValid =
false;
    }
   
else
    {
       
int Number;
       
bool isNumber = int.TryParse(args.Value, out Number);
       
if (isNumber && Number >= 0 && (Number % 2) == 0)
        {
            args.IsValid =
true;
        }
       
else
        {
            args.IsValid =
false;
        }
    }
}
ValidationSummary control in asp.net

ValidationSummary control is used to display a summary of all validation errors occurred in a Web page, at one place. In general, in a real time applications, it is very common to display a red star symbol next to the input control where the error occurred, and then the detailed error message in the validation summary control as shown below.

ValidationSummary control example in asp.net



Properties specific to the validation summary control: HeaderText - The header text for the validation summary control
ShowSummary - Whether to display the summary text of all the validation errors
ShowMessageBox - Whether to display a message box with all the validation errors
DisplayMode - Display format for the summary.

DisplayMode can be List, BulletList, SingleParagraph



HTML of the ASPX Page: <div style="font-family: Arial">
    <table style="border: 1px solid black">
        <tr>
            <td colspan="2">
                <h2>User Registration</h2>
            </td>
        </tr>
        <tr>
            <td>
                <b>Email</b>
            </td>
            <td>
                <asp:TextBox ID="txtEmail" runat="server" Width="100px">
                </asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail"
                runat="server" ForeColor="Red"
                ErrorMessage="Email is required"
                ControlToValidate="txtEmail" Display="Dynamic" Text="*">
                </asp:RequiredFieldValidator>
                <asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail"
                runat="server" ErrorMessage="Invalid Email Format"
                ControlToValidate="txtEmail" ForeColor="Red"
                ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                Text="*">
                </asp:RegularExpressionValidator>
            </td>
        </tr>
        <tr>
            <td>
                <b>User Name</b>
            </td>
            <td>
                <asp:TextBox ID="txtUserName" runat="server" Width="100px">
                </asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidatorUserName"
                runat="server" ForeColor="Red"
                ErrorMessage="Username is required"
                ControlToValidate="txtUserName" Display="Dynamic" Text="*">
                </asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td>
                <b>Password</b>
            </td>
            <td>
                <asp:TextBox ID="txtPassword" runat="server" Width="100px"
                TextMode="Password"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidatorPassword"
                runat="server" ForeColor="Red"
                ErrorMessage="Password is required"
                ControlToValidate="txtPassword" Display="Dynamic" Text="*">
                </asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td>
                <b>Confirm Password</b>
            </td>
            <td>
                <asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password"
                Width="100px"></asp:TextBox>
                <asp:CompareValidator ID="CompareValidatorPassword" runat="server"
                ErrorMessage="Password and Confirm Password must match"
                ControlToValidate="txtConfirmPassword" ControlToCompare="txtPassword"
                Operator="Equal" Type="String" ForeColor="Red" Text="*">
                </asp:CompareValidator>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Button ID="btnSubmit" runat="server" Text="Save"
                    onclick="btnSubmit_Click" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:ValidationSummary ID="ValidationSummary1" runat="server"
                ForeColor="Red" HeaderText="Page Errors" ShowMessageBox="True"
                ShowSummary="true" DisplayMode="List"
                />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Label ID="lblStatus" runat="server" Font-Bold="true"></asp:Label>
            </td>
        </tr>
    </table>
</div>
ValidationGroups in asp.net
we will discuss about ValidationGroups and CausesValidation.
Consider the image below. 
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjC5Q3maJy_SZu1VDskrXzgeKzVHBoakRKlG7iOOB-b8bNO79GRHCPV-Evn09-feHWXNKn_Um5x2OnjxLttDkX4osOiRdgEwq24ZLtrHr_ktpDyKeLingS4ctQ_nEsJGqIOBvjrp5RAJM89/s1600/ValidationGroups+in+asp.net.png

The first problem here is that, when I click the Clear button, Form validation still happens. When I click the clear button, I just want to clear the textboxes in the Registration section. Validations doesn't make any sense here. So, how do I prevent validation from happening? 

Just, set the CausesValidation property of the button control to false. 



The second problem, is that when I click the Login button, only fields in the Login section(UserName and Password) needs to be validated. Along the same lines when I click the "Register" button, only fields in the Registration section(Email, UserName, Password and ConfirmPassword) needs to validated. If we don't use validation groups, then by default, whenever, you click a button, all the validation controls on the page get validated.

So, when you click the login button, and if you want only, the fields in the Login section(UserName and Password) to be validated, then set, the ValidationGroup property of the validation controls and the login button control to the same group name. Use a different group name for the validation controls and register button, in the registration section.



HTML of the aspx page: <div style="font-family: Arial">
<table>
    <tr>
        <td style="vertical-align: top">
            <table style="border: 1px solid black">
                <tr>
                    <td colspan="2">
                        <h2>
                            Login</h2>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>User Name</b>
                    </td>
                    <td>
                        <asp:TextBox ID="txtUN" runat="server" Width="100px">
                        </asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorUN"
                            runat="server" ForeColor="Red"
                            ErrorMessage="Username is required"
                            ControlToValidate="txtUN" Display="Dynamic"
                            Text="*" ValidationGroup="Login">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Password</b>
                    </td>
                    <td>
                        <asp:TextBox ID="TextBoxPWD" runat="server" Width="100px"
                        TextMode="Password"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorPWD"
                            runat="server" ForeColor="Red"
                            ErrorMessage="Password is required"
                            ControlToValidate="TextBoxPWD" Display="Dynamic"
                            Text="*" ValidationGroup="Login">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Button ID="btnLogin" ValidationGroup="Login"
                        runat="server" Text="Login"
                        onclick="btnLogin_Click" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:ValidationSummary ValidationGroup="Login"
                            ID="ValidationSummary2" runat="server"
                            ForeColor="Red" HeaderText="Page Errors"
                            ShowMessageBox="True" ShowSummary="true"
                            DisplayMode="List" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Label ID="lblLoginStatus" runat="server"
                        Font-Bold="true"></asp:Label>
                    </td>
                </tr>
            </table>
        </td>
        <td>
            &nbsp;&nbsp;
        </td>
        <td>
            <table style="border: 1px solid black">
                <tr>
                    <td colspan="2">
                        <h2>
                            User Registration</h2>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Email</b>
                    </td>
                    <td>
                        <asp:TextBox ID="txtEmail" runat="server" Width="100px">
                        </asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail"
                            runat="server" ForeColor="Red"
                            ErrorMessage="Email is required"
                            ControlToValidate="txtEmail" Display="Dynamic"
                            Text="*" ValidationGroup="Registration">
                        </asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator
                            ID="RegularExpressionValidatorEmail"
                            runat="server"
                            ErrorMessage="Invalid Email Format"
                            ControlToValidate="txtEmail" ForeColor="Red"
                            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                            Text="*"
                            ValidationGroup="Registration">
                        </asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>User Name</b>
                    </td>
                    <td>
                        <asp:TextBox ID="txtUserName" runat="server" Width="100px">
                        </asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorUserName"
                            runat="server" ForeColor="Red"
                            ErrorMessage="Username is required"
                            ControlToValidate="txtUserName" Display="Dynamic"
                            Text="*" ValidationGroup="Registration">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Password</b>
                    </td>
                    <td>
                        <asp:TextBox ID="txtPassword" runat="server"
                        Width="100px" TextMode="Password"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorPassword"
                            runat="server" ForeColor="Red"
                            ErrorMessage="Password is required"
                            ControlToValidate="txtPassword" Display="Dynamic"
                            Text="*" ValidationGroup="Registration">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Confirm Password</b>
                    </td>
                    <td>
                        <asp:TextBox ID="txtConfirmPassword" runat="server"
                            TextMode="Password" Width="100px"></asp:TextBox>
                        <asp:CompareValidator ID="CompareValidatorPassword"
                            runat="server"
                            ErrorMessage="Password and Confirm Password must match"
                            ControlToValidate="txtConfirmPassword"
                            ControlToCompare="txtPassword" Operator="Equal"
                            Type="String" ForeColor="Red" Text="*"
                            ValidationGroup="Registration">
                        </asp:CompareValidator>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Button ID="btnSubmit" runat="server" Text="Register"
                        OnClick="btnSubmit_Click" ValidationGroup="Registration"/>
                        &nbsp;
                        <asp:Button ID="btnClear" runat="server" onclick="btnClear_Click"
                        CausesValidation="false" Text="Clear" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:ValidationSummary ID="ValidationSummary1" runat="server"
                            ForeColor="Red" HeaderText="Page Errors" ShowMessageBox="True"
                            ShowSummary="true" DisplayMode="List"
                            ValidationGroup="Registration"/>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Label ID="lblStatus" runat="server"
                        Font-Bold="true"></asp:Label>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>
</div>

Code-Behind: protected void btnSubmit_Click(
object sender, EventArgs e)
{
   
if (Page.IsValid)
    {
        lblStatus.Text =
"No registration validation Errors";
        lblStatus.ForeColor = System.Drawing.
Color.Green;
    }
   
else
    {
        lblStatus.Text =
"Registration validation Errors";
        lblStatus.ForeColor = System.Drawing.
Color.Red;
    }
}

protected void btnClear_Click(object sender, EventArgs e)
{
    txtEmail.Text = "";
    txtUserName.Text = "";
    txtPassword.Text = "";
    txtConfirmPassword.Text = "";
}

protected void btnLogin_Click(object sender, EventArgs e)
{
   
if (Page.IsValid)
    {
        lblLoginStatus.Text =
"No Login Validation Errors";
        lblStatus.ForeColor = System.Drawing.
Color.Green;
    }
   
else
    {
        lblStatus.Text =
"Login validation errors";
        lblStatus.ForeColor = System.Drawing.
Color.Red;
    }
}
 
Adrotator control in asp.net


Adrotator control is used to display random ads. The ads information can be stored in an xml file or in a database table. In this video we will discuss about using an XML file.

XML file attributes
ImageUrl - The URL of the image to display
NavigateUrl - The URL to navigate to, when the ad is clicked
AlternateText - The text to use if the image is missing
Keyword - Used by the adrotator control to filter ads
Impressions - A numeric value (a weighting number) that indicates the likelihood of how often the ad is displayed. 

Create an asp.net web application project, and add an XML file. Name the XML file as AdsData.xml. Copy and paste the following in the XML file.
<?xml version="1.0" encoding="utf-8" ?>
<Advertisements>
  <Ad>
    <ImageUrl>~/Images/Google.png</ImageUrl>
    <NavigateUrl>http://google.com</NavigateUrl>
    <AlternateText>Please visit http://www.Google.com</AlternateText>
    <Impressions>10</Impressions>
  </Ad>
  <Ad>
    <ImageUrl>~/Images/Pragim.png</ImageUrl>
    <NavigateUrl>http://pragimtech.com</NavigateUrl>
    <AlternateText>Please visit http://www.pragimtech.com</AlternateText>
    <Impressions>20</Impressions>
  </Ad>
  <Ad>
    <ImageUrl>~/Images/Youtube.png</ImageUrl>
    <NavigateUrl>http://Youtube.com</NavigateUrl>
    <AlternateText>Please visit http://www.Youtube.com</AlternateText>
    <Impressions>40</Impressions>
  </Ad>
</Advertisements>



Create an Images folder in the project, and add the following images. https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixmVSTmsi1NzHn_j7ECa7aZW6eppjMcfsNwnihPhnSY-6xRvZtJ_GBqoDnylzxxkjWQlFfE9TZ-XUbCb0efWJF3jBXagQL-4MClDT3kk6ROZnQKmo_LDAbGuKzzg1FqpJWNvIwXTOP0de2/s400/Google.png

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi02ujDpTQHoYeasWvBe6p-7AHh4eiuhetaTefGOqUvvD6y8-sKQs8eDlrOi4_rapG1X6peFBR5ZHmRIYeAeXRpshDB5hhnBqQ7HFJNN0y2NmvVuiWmrjNoOFY8Ulh4LX8Vx8IvsKtf8JLd/s400/Pragim.png

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgLSYd2j-mqbbIDDN9AtZ7A46N-aEYXT_SKytn1G3B599Bu4fVbtoRvgJyN-Z_e7FBI5ouNiKW7Z-w8LtfgE5gtbLMW_Kco1-o_fuTvwTlHGqsSjVs7wvtA0KHpSOn0M_AoPX3aCroSbz2G/s400/Youtube.png

Drag and Drop the AdRotator control on the webform. Set AdvertisementFile="~/AdsData.xml".
<asp:AdRotator AdvertisementFile="~/AdsData.xml" ID="AdRotator1" runat="server" />

To open the target web page in a separate browser window, set Target="_blank"

Use KeyWord attribute to filter ads.

The KeywordFilter and AdvertisementFile properties can be changed at runtime also. Changing the KeywordFilter at runtime could be very useful. For example, when the AdRotator control is on a master page, and if you want to change the KeywordFilter on each content page based on the keyword density, so that, only the ads targeting the page content can be displayed. More on this, when we discuss about master pages in a later video session.

Asp.net calendar control

In this video we will learn about the asp.net calendar control. Any time you want your users of the application, to provide a date, it is better to provide a calendar control from which they can select the date. In this session we will see how to do it.



Drag and drop a TextBox, ImageButton and a Calendar control on the webform. Create an Image folder and add the following Calendar.png to the Images folder.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjh9JyODanxw1p2eXdixea5Ikkn7ZW1mjOO6alEA4VQi_3WWIp5JQUmR7oHbn-vztk0piJRfMdBTMsZTsGECEfOHx-ZRHUd_NS1JYsubKxB_c5NDhnFw6i3qj_h9lTR9Lx95PSRTxUiGSnb/s1600/Calendar.png

Set the ImageUrl property of the image button to Calendar.png
ImageUrl="~/Images/Calendar.png"

HTML of the ASPX page
<asp:TextBox ID="TextBox1" runat="server" Width="115px"></asp:TextBox>
<asp:ImageButton ID="ImageButton1" runat="server"
    ImageUrl="~/Images/Calendar.png" onclick="ImageButton1_Click" />
<asp:Calendar ID="Calendar1" runat="server" ondayrender="Calendar1_DayRender"
    onselectionchanged="Calendar1_SelectionChanged"></asp:Calendar>



Code-Behind page code
protected void Page_Load(object sender, EventArgs e)
{
   
if (!IsPostBack)
    {
        Calendar1.Visible =
false;
    }
}
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
   
if (Calendar1.Visible)
    {
        Calendar1.Visible =
false;
    }
   
else
    {
        Calendar1.Visible =
true;
    }
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
    TextBox1.Text = Calendar1.SelectedDate.ToShortDateString();
    Calendar1.Visible =
false;
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
   
if (e.Day.IsWeekend || e.Day.IsOtherMonth)
    {
        e.Day.IsSelectable =
false;
        e.Cell.BackColor = System.Drawing.
Color.LightGray;
    }
}

Date Conversion methods
Response.Write(
"ToString() - " + DateTime.Now.ToString() + "<br/>");
Response.Write(
"ToLongDateString() - " + DateTime.Now.ToLongDateString() + "<br/>");
Response.Write(
"ToShortDateString() - " + DateTime.Now.ToShortDateString() + "<br/>");
Response.Write(
"ToLongTimeString() - " + DateTime.Now.ToLongTimeString() + "<br/>");
Response.Write(
"ToShortTimeString() - " + DateTime.Now.ToShortTimeString() + "<br/>");

Output:
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6jjQJJ0IkxE7s_2BEUyfOl_uBI_pCJKvsBlJ0QQMpAy3hv9Lxf6CVPWyDKNP20FEAtBnzooPtnMMgTjL841snOzNrcjg5JZDBOaAHDgPMPf2krf6FyPb5UVPEXG3Ez0GPyj8qKjydR4Hd/s1600/Date+Conversion+methods.png

DateTime format strings
Response.Write(
"d - " + DateTime.Now.ToString("d") + "<br/>");
Response.Write(
"D - " + DateTime.Now.ToString("D") + "<br/>");
Response.Write(
"dd/MM/yyyy - " + DateTime.Now.ToString("dd/MM/yyyy") + "<br/>");
Response.Write(
"dd/MMMM/yyyy - " + DateTime.Now.ToString("dd/MMMM/yyyy") + "<br/>");
Response.Write(
"dd/MMMM/yy - " + DateTime.Now.ToString("dd/MMMM/yy") + "<br/>");
Response.Write(
"MM/dd/yy - " + DateTime.Now.ToString("MM/dd/yy") + "<br/>");

Output
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhwn6eutD4S6aDlrFm-Hvm9wYe-kRBKTfMQTzeOt8HziFdY1uWlEP3AnGeNUlaD5Jy67_TaasjdlTfjN7ygkNVwKzD9tdjyENahofWAXfZsVtefNdVl8u_66PtG-lBGtnRqDQ7WgBtv8aBx/s1600/DateTime+format+strings.png

Asp.net calendar control properties and events


Useful Properties of the Calendar control
Caption - This is a string read/write property.
CaptionAlign - Used to align the caption.
DayHeaderStyle - Style properties that can be used to customize the look and feel of the day header in the calendar
DayNameFormat - Can be Full, Short, FirstLetter, FirstTwoLetters, Shortest
DayStyle - Style properties that can be used to customize the look and feel of the day in the calendar
FirstDayOfWeek - Which day of the week is displayed first
NextPrevFormat - Can be ShortMonth, FullMonth, CustomText
NextMonthText - The text to use for the next month button.
PrevMonthText - The text to use for the previous month button.
SelectionMode - Can be Day, DayWeek, DayWeekMonth. Determines if Days, Weeks and Months are selectable.



If the SelectionMode is set to Day, then the user can select only one day. In this case to retrieve the selected date, we use SelectedDate property of the calendar as shown below.
Response.Write(Calendar1.SelectedDate.ToShortDateString());

However, if the SelectionMode is set to DayWeek or DayWeekMonth. In this case of you want to retrieve all the selected dates within the selected week or month, then SelectedDates property can be used as shown below. Using SelectedDate, property returns only the first selected date of the week or month.
foreach (DateTime selectedDate in Calendar1.SelectedDates)
{
    Response.Write(selectedDate.ToShortDateString() +
"<br/>");
}

Events:
SelectionChanged - Fires when the date,week or Month selection is changed, by the user.
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
   
foreach (DateTime selectedDate in Calendar1.SelectedDates)
    {
        Response.Write(selectedDate.ToShortDateString() +
"<br/>");
    }
}



DayRender - Fires as a day in the calendar control is being rendered.
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
   
if (!e.Day.IsOtherMonth && e.Day.Date.Day % 2 == 0)
    {
        e.Cell.Text =
"x";
        e.Cell.Font.Bold =
true;
        e.Cell.ForeColor = System.Drawing.
Color.White;
        e.Cell.BackColor = System.Drawing.
Color.Red;
        e.Cell.ToolTip =
"Booked";
    }
   
else
    {
        e.Cell.ToolTip =
"Available";
    }
}

VisibleMonthChanged - Fires when the visible month is changed by the user
protected void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
{
    Response.Write(
"Month changed from ");
    Response.Write(GetMonthName(e.PreviousDate.Month));
    Response.Write(
" to ");
    Response.Write(GetMonthName(e.NewDate.Month));
}
private string GetMonthName(int MonthNumber)
{
   
switch (MonthNumber)
    {
    case 1:
        return
"Jan";
    case 2:
        return
"Feb";
    case 3:
        return
"Mar";
    case 4:
        return
"Apr";
    case 5:
        return
"May";
    case 6:
        return
"Jun";
    case 7:
        return
"Jul";
    case 8:
        return
"Aug";
    case 9:
        return
"Sep";
    case 10:
        return
"Oct";
    case 11:
        return
"Nov";
    case 12:
        return
"Dec";
    default:
        return
"Invalid Month";
    }
}

Hidden field in asp.net


In this video we will learn about HiddenField in asp.net

The HiddenField control is used to store a value that needs to be persisted across posts to the server, but you don't want the control or it's value visible to the user. For example, when editing and updaing an employee record, we don't want the user to see the EmployeeId. So, we will store the EmployeeId in a HiddenField, so that it can then be used on the server to update the correct employees record.

SQL Script
Create Table tblEmployees
(
 Id
int Primary Key,
 Name
nvarchar(50),
 Gender
nvarchar(10),
 DeptName
nvarchar(10)
)

Insert into tblEmployees values(201, 'Mark', 'Male', 'IT')
Insert into tblEmployees values(202, 'Steve', 'Male', 'Payroll')
Insert into tblEmployees values(203, 'John', 'Male', 'HR')



HTML of the ASPX Page
<asp:HiddenField ID="HiddenField1" runat="server" />
<table>
    <tr>
        <td>Name:</td>
        <td>
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            </td>
    </tr>
    <tr>
        <td>Gender:</td>
        <td>
            <asp:TextBox ID="txtGender" runat="server"></asp:TextBox>
            </td>
    </tr>
    <tr>
        <td>Department:</td>
        <td>
            <asp:TextBox ID="txtDept" runat="server"></asp:TextBox>
            </td>
    </tr>
</table>
<asp:Button ID="Button1" runat="server" Text="Update Employee"
    onclick="Button1_Click" />&nbsp;
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
    Text="Load Employee" />



Code-Behind code:
protected void Page_Load(object sender, EventArgs e)
{
   
if (!IsPostBack)
    {
        LoadEmployee();
    }
}

private void LoadEmployee()
{
   
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
   
using (SqlConnection con = new SqlConnection(CS))
    {
       
string sqlQuery = "Select Id, Name, Gender, DeptName from tblEmployees where Id=202";
       
SqlCommand cmd = new SqlCommand(sqlQuery, con);
        con.Open();
       
using (SqlDataReader rdr = cmd.ExecuteReader())
        {
           
while (rdr.Read())
            {
                txtName.Text = rdr[
"Name"].ToString();
                txtGender.Text = rdr[
"Gender"].ToString();
                txtDept.Text = rdr[
"DeptName"].ToString();
                HiddenField1.Value = rdr[
"Id"].ToString();
            }
        }
    }
}

protected void Button1_Click(object sender, EventArgs e)
{
   
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
   
using (SqlConnection con = new SqlConnection(CS))
    {
       
string sqlQuery = "Update tblEmployees set Name=@Name, Gender=@Gender, DeptName=@DeptName where Id=@Id";
       
SqlCommand cmd = new SqlCommand(sqlQuery, con);
               
        cmd.Parameters.AddWithValue(
"@Name", txtName.Text);
        cmd.Parameters.AddWithValue(
"@Gender", txtGender.Text);
        cmd.Parameters.AddWithValue(
"@DeptName", txtDept.Text);
        cmd.Parameters.AddWithValue(
"@Id", HiddenField1.Value);
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();

        txtName.Text = "";
        txtDept.Text = "";
        txtGender.Text = "";
    }
}

protected void Button2_Click(object sender, EventArgs e)
{
    LoadEmployee();
}

HiddenField:
1. Value property of the HiddenFiled is used to Get or set the value.
2. The value is stored as string
3. ViewState uses HiddenFiled to maintain state across postback
4. HiddenField is rendered as an <input type= "hidden"/> element

Alternatives for HiddenField:
View state, QueryStrings, session state, and cookies can be used as an alternative for HiddenField. Session state and cookies will be accessible from other pages as well, and will be available untill their timeout has reached. Where as ViewState and HiddenField data, is available only on that page and the data is lost when you navigate away from the page.

Advantages of HiddenField:
HiddenFiled data is lost when you navigate away from the page. Doesn't require any explicit cleanup task.
HiddenField is accessible to client-side scripts
<script type="text/javascript">
    function GetHiddenFieldValue() 
    {
        alert(document.getElementById('HiddenField1').value);
    }
</script>

Disadvantage of HiddenField:
Hidden field data can be seen, by viewing the page source. Never, use HiddenFiled to store confidential data

Multiview control in asp.net


In this video we will discuss about the Multiview and View controls in asp.net. As the name states, a multiview is made up of multiple view controls, and each view control inturn can have controls inside it.
The HTML below shows a multiview, with 3 views
<asp:MultiView ID="MultiView1" runat="server">
    <asp:View ID="View1" runat="server">
    </asp:View>  
    <asp:View ID="View2" runat="server">
    </asp:View>
    <asp:View ID="View3" runat="server">
    </asp:View>
</asp:MultiView>



Let's create a simple example, where we want to capture employee information on a step by step basis.
1. First capture Employee Personal details
2. Next capture Employee contact details
3. Show summary for confirmation. Upon confirmation, save the data to a database table

HTML of the aspx page
<div style="font-family: Arial">
    <asp:MultiView ID="multiViewEmployee" runat="server">
        <asp:View ID="viewPersonalDetails" runat="server">
            <table style="border:1px solid black">
                <tr>
                    <td colspan="2">
                        <h2>Step 1 - Personal Details</h2>
                    </td>
                </tr>
                <tr>
                    <td>First Name</td>
                    <td>
                        <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Last Name</td>
                    <td>
                        <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Gender</td>
                    <td>
                        <asp:DropDownList ID="ddlGender" runat="server">
                            <asp:ListItem Text="Male" Value="Male"></asp:ListItem>
                            <asp:ListItem Text="Female" Value="Female"></asp:ListItem>
                        </asp:DropDownList>
                    </td>
                </tr>
                <tr>
                    <td colspan="2" style="text-align:right">
                        <asp:Button ID="btnGoToStep2" runat="server"
                        Text="Step 2 >>" onclick="btnGoToStep2_Click" />
                    </td>
                </tr>
            </table>
        </asp:View>  
        <asp:View ID="viewContactDetails" runat="server">
            <table style="border:1px solid black">
                <tr>
                    <td colspan="2">
                        <h2>Step 2 - Contact Details</h2>
                    </td>
                </tr>
                <tr>
                    <td>Email Address</td>
                    <td>
                        <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>Mobile Number</td>
                    <td>
                        <asp:TextBox ID="txtMobile" runat="server"></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="btnBackToStep1" runat="server" Text="<< Step 1"
                            onclick="btnBackToStep1_Click" />
                    </td>
                    <td style="text-align:right">
                        <asp:Button ID="btnGoToStep3" runat="server" Text="Step 3 >>"
                            onclick="btnGoToStep3_Click" />
                    </td>
                </tr>
            </table>
        </asp:View>
        <asp:View ID="viewSummary" runat="server">
            <table style="border:1px solid black">
                <tr>
                    <td colspan="2"><h2>Step 3 - Summary</h2></td>
                </tr>
                <tr>
                    <td colspan="2"><h3>Personal Details</h3></td>
                </tr>
                <tr>
                    <td>First Name</td>
                    <td>
                        :<asp:Label ID="lblFirstName" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td>Last Name</td>
                    <td>
                        :<asp:Label ID="lblLastName" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td>Gender</td>
                    <td>
                        :<asp:Label ID="lblGender" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td colspan="2"><h3>Contact Details</h3></td>
                </tr>
                <tr>
                    <td>Email Address</td>
                    <td>
                        :<asp:Label ID="lblEmail" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td>Mobile Number</td>
                    <td>
                        :<asp:Label ID="lblMobile" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Button ID="Button1" runat="server" Text="<< Step 2"
                            onclick="Button1_Click" />
                    </td>
                    <td style="text-align:right">
                        <asp:Button ID="Button2" runat="server" Text="Submit >>"
                            onclick="Button2_Click" />
                    </td>
                </tr>
            </table>
        </asp:View>
    </asp:MultiView>
</div>



Code-Behind Page:
protected void Page_Load(object sender, EventArgs e)
{
   
if (!IsPostBack)
    {
        multiViewEmployee.ActiveViewIndex = 0;
    }
}
       
protected void btnGoToStep2_Click(object sender, EventArgs e)
{
    multiViewEmployee.ActiveViewIndex = 1;
}

protected void btnBackToStep1_Click(object sender, EventArgs e)
{
    multiViewEmployee.ActiveViewIndex = 0;
}

protected void btnGoToStep3_Click(object sender, EventArgs e)
{
    lblFirstName.Text = txtFirstName.Text;
    lblLastName.Text = txtLastName.Text;
    lblGender.Text = ddlGender.SelectedValue;

    lblEmail.Text = txtEmail.Text;
    lblMobile.Text = txtMobile.Text;

    multiViewEmployee.ActiveViewIndex = 2;
}

protected void Button1_Click(object sender, EventArgs e)
{
    multiViewEmployee.ActiveViewIndex = 1;
}

protected void Button2_Click(object sender, EventArgs e)
{
   
// Write ado.net code to save data to a database table
     Response.Redirect("~/Confirmation.aspx");
}

ActiveViewIndex property of the Multiview control is used to determine, the view that is visible or active.

This can also be achieved using the wizard control. We will discuss about wizard control in the next video session.

Another way to achieve this, is by creating multiple webforms and passing data between webforms using
1. Cookies
2. Query Strings
3. Session variables

We will discuss about these different techniques and their advantages and disadvantages in a later video session.

Asp.net Wizard control properties


Properties:
ActiveStepIndex - Used to set or get the ActiveStepIndex of the wizard control
DisplayCancelButton - Determines the visibility of the cancel button in the wizard control
CancelButtonImageUrl - If the cancel button type is set to Image button. Then set this property to specify the image.
CancelButtonStyle - The style properties to customize the cancel button
CancelButtonText - If the cancel button type is set to Link or Button, then set this property to specify the Text of the button.
CancelButtonType - Use to Specify the type of cancel button. This can be Button, Image or Link.
CancelDestinationPageUrl - The destination page to redirect to, when the cancel button is clicked. This can be a page with in the application or an external website.



DisplaySideBar - Determines if the wizard sidebar should be displayed or not
FinishCompleteButtonType - The button type of the finish step's finish button
FinishPreviousButtonType - The button type of the finish step's previous button
HeaderStyle - The style properties to customize the wizard header
HeaderText - The header text of the wizard control
protected void Page_PreRender(object sender, EventArgs e)
{
   
if (Wizard1.ActiveStepIndex == 1)
    {
        Wizard1.HeaderText =
"Contact Details";
    }
   
else if (Wizard1.ActiveStepIndex == 2)
    {
        Wizard1.HeaderText =
"Summary";
    }
}



NavigationButtonStyle - The style properties to customize the wizard navigation buttons
NavigationStyle - The style properties to customize the navigation area that holds the navigation buttons
SideBarButtonStyle - The style properties to customize the wizard sidebar buttons
SideBarStyle - The style properties to customize the wizard sidebar
StartNextButtonType - The type of the start step's next button
StepNextButtonType - The button type of next step button
StepPreviousButtonType - The button type of previous step button
StepStyle - The style properties to customize the wizard steps

Note: WizardSteps can be added in the HTML source or using the WizardSteps collection editor.

Asp.net Wizard control events

Drag and drop a wizard control on the webform. Right click on the wizard control and select the properties. Click on the events icon. This displays all the events of the wizard control.

To generate the event handler method for ActiveStepChanged event, double click on the textbox next to the event. Follow the same process to generate the event handler methods for the rest of the events of the wizard control.



HTML of the aspx page:
<div style="font-family: Arial">
    <asp:Wizard ID="Wizard1" runat="server"
        onactivestepchanged="Wizard1_ActiveStepChanged"
        oncancelbuttonclick="Wizard1_CancelButtonClick"
        onnextbuttonclick="Wizard1_NextButtonClick"
        onfinishbuttonclick="Wizard1_FinishButtonClick"
        onpreviousbuttonclick="Wizard1_PreviousButtonClick"
        onsidebarbuttonclick="Wizard1_SideBarButtonClick">
        <SideBarStyle VerticalAlign="Top" />
        <WizardSteps>
            <asp:WizardStep runat="server" title="Step 1">
                <asp:CheckBox ID="chkBoxCancel" Text="Cancel Navigation" runat="server" />
            </asp:WizardStep>
            <asp:WizardStep runat="server" title="Step 2">
            </asp:WizardStep>
            <asp:WizardStep runat="server" title="Step 3">
            </asp:WizardStep>
        </WizardSteps>
    </asp:Wizard>
</div>



Code-Behind page code:
// ActiveStepChanged - Fires when the active step of the index is changed.
protected void Wizard1_ActiveStepChanged(object sender, EventArgs e)
{
    Response.Write(
"Active Step Changed to " + Wizard1.ActiveStepIndex.ToString() + "<br/>");
}
// CancelButtonClick - Fires when the cancel button of the wizard control is clicked. 
// To display the cancel button, set DisplayCancelButton=True.
protected void Wizard1_CancelButtonClick(object sender, EventArgs e)
{
    Response.Redirect(
"Cancel Button Clicked");
}
// NextButtonClick - Fires when the next button of the wizard control is clicked. 
protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)
{
    Response.Write(
"Current Step Index = " + e.CurrentStepIndex.ToString() + "<br/>");
    Response.Write(
"Next Step Index = " + e.NextStepIndex.ToString() + "<br/>");
   
if (chkBoxCancel.Checked)
    {
        Response.Write(
"Navigation to next step will be cancelled");
        e.Cancel =
true;
    }
}
// FinishButtonClick - Fires when the finish button is clicked
protected void Wizard1_FinishButtonClick(object sender, WizardNavigationEventArgs e)
{
    Response.Write(
"Finish button clicked <br/>");
    Response.Write(
"Current Step Index = " + e.CurrentStepIndex.ToString() + "<br/>");
    Response.Write(
"Next Step Index = " + e.NextStepIndex.ToString());
}
// PreviousButtonClick - Fires when the previous button is clicked
protected void Wizard1_PreviousButtonClick(object sender, WizardNavigationEventArgs e)
{
    Response.Write(
"Previous button clicked<br/>");
}
// SideBarButtonClick - Fires when the sidebar button is clicked
protected void Wizard1_SideBarButtonClick(
object sender, WizardNavigationEventArgs e)
{
    Response.Write(
"Sidebar button clicked<br/>");
}

UseSubmitBehavior property of the Button control


In this video we will discuss about the UseSubmitBehavior property of the asp.net Button control. Let us understand the use of this property with an example.

Design a webform with a TextBox, Label and 2 Button controls as shown in the image below.
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRQvPY3H_fbgZMHUW6rXKs2ZzynnFMwtsw7o9kG__Y5F9_UVitb5qfP70v4U9I5BPSFqzwm7c02MFdxFLyRuNFMjV6aqENj3oqZsduS3lGr64Vs9TgdiVp9E_7Zd-HJJ9-ik0_OVF4yHN3/s1600/UseSubmitBehavior+property+example.png



For your convinience, I have included the HTML of the aspx page.
<div style="font-family: Arial">
    <strong>Name : </strong>
    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    <br />
    <br />
    <asp:Button ID="btnClear" runat="server" onclick="btnClear_Click" Text="Clear"/>
    &nbsp;
    <asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click" Text="Submit" />
    <br />
    <br />
    <asp:Label ID="lblMessage" runat="server" Font-Bold="True" ForeColor="#009933"></asp:Label>
</div>



Dobule click the Clear and Submit buttons, to generate the event handlers, and paste the following code in the code behind page.
protected void btnSubmit_Click(object sender, EventArgs e)
{
    lblMessage.Text =
"You enetered: " + txtName.Text;
}

protected void btnClear_Click(object sender, EventArgs e)
{
    txtName.Text = "";
}

Now, run the web application project. Enter a name in the textbox and hit the enter key on the keyboard. Notice that the cancel button has the submit behaviour.

In the HTML of the aspx page, set UseSubmitBehavior="false" for the clear button.
<asp:Button ID="btnClear" UseSubmitBehavior="false" runat="server"
onclick="btnClear_Click" Text="Clear"/>

Now, run the web application project again. Enter a name in the textbox and hit the enter key on the keyboard. Notice that the submit button has the submit behaviour, as expected.

The UseSubmitBehavior property specifies if the Button control uses the browser's built-in submit function or the ASP.NET postback mechanism.

This property is TRUE by default. When set to FALSE, ASP.NET adds a client-side script to post the form. To view the client side script added by the ASP.NET, right click on the broswer and view source.

Asp.net wizard control templates


we will look at the advanced features of the wizard control like
1. Set focus to the first control in the wizard step when the page loads, so that the user can start typing into the textbox directly.
2. Attach javascript to the Next, Previous and Finish buttons, to display a confirmation dialog box before the user moves to the next step.
3. Setting UseSubmitBehavior="true" for the Previous button in the wizard control.



In the HTML below, we have a wizard control with 3 steps. Each step has a TextBox control. 
<asp:Wizard ID="Wizard1" runat="server">
    <WizardSteps>
        <asp:WizardStep ID="WizardStep1" runat="server" Title="Step 1">
            <asp:TextBox ID="Step1TextBox" runat="server"></asp:TextBox>
        </asp:WizardStep>
        <asp:WizardStep ID="WizardStep2" runat="server" Title="Step 2">
            <asp:TextBox ID="Step2TextBox" runat="server"></asp:TextBox>
        </asp:WizardStep>
        <asp:WizardStep ID="WizardStep3" runat="server" Title="Step 3">
            <asp:TextBox ID="Step3TextBox" runat="server"></asp:TextBox>
        </asp:WizardStep>
    </WizardSteps>
</asp:Wizard>



The following code, sets the focus to the correct textbox, based on the ActiveStepIndex. Make sure you have this code in the Page_PreRender event. Copying this code in the Page_Load() event will not work correctly. This is because the ActiveStepIndex is changed on the Button click event which happens after the Page_Load() event. As the Page_PreRender() events occurs after the Button_Click event, the code works correctly as expected.
protected void Page_PreRender(object sender, EventArgs e)
{
   
if (Wizard1.ActiveStepIndex == 0)
    {
        Step1TextBox.Focus();
    }
   
else if (Wizard1.ActiveStepIndex == 1)
    {
        Step2TextBox.Focus();
    }
   
else if (Wizard1.ActiveStepIndex == 2)
    {
        Step3TextBox.Focus();
    }
}

To attach, javascript to the buttons in the navigation bar(next, previous, Finish), we need to use Navigation Templates. By default, the wizard control generates these buttons automatically. To make the wizard control use navigation templates and attach javascript
1. Right click on the wizard control and select "Show smart tag"
2. Click on "Convert To Start Navigation Template".
3. Now in the HTML source, specify the javascript that needs to be executed in response to the OnClientClick event.
<asp:Wizard ID="Wizard1" runat="server">
    <StartNavigationTemplate>
        <asp:Button ID="StartNextButton" runat="server" CommandName="MoveNext" Text="Next"
            OnClientClick="return confirm('Are you sure you want to go to next step');" />
    </StartNavigationTemplate>
    <WizardSteps>
        <asp:WizardStep ID="WizardStep1" runat="server" Title="Step 1">
            <asp:TextBox ID="Step1TextBox" runat="server"></asp:TextBox>
        </asp:WizardStep>
        <asp:WizardStep ID="WizardStep2" runat="server" Title="Step 2">
            <asp:TextBox ID="Step2TextBox" runat="server"></asp:TextBox>
        </asp:WizardStep>
        <asp:WizardStep ID="WizardStep3" runat="server" Title="Step 3">
            <asp:TextBox ID="Step3TextBox" runat="server"></asp:TextBox>
        </asp:WizardStep>
    </WizardSteps>
</asp:Wizard>

Use StepNavigationTemplate, to attach javascript to the Next and Previous buttons on all wizard steps, where StepType="Step"
Use FinishNavigationTemplate, to attach javascript to the Finish button on the last step of the wizard control.

It is also possible to add javascript in code. To add the javascript using code for the Next button, in a wizard step, where StepType="Step"
protected void Page_Load(object sender, EventArgs e)
{
   
if (!IsPostBack)
    {
        Button btnNext = (
Button)Wizard1.FindControl("StepNavigationTemplateContainerID").FindControl("StepNextButton");
        btnNext.Attributes.Add(
"onclick", "return confirm('Are you sure you want to move to the next step');");
    }
}

To make the next button of the wizard control the default button, set UseSubmitBehavior=False for the Previous button. So that, when the user hits the Enter key, after entering the required data, the user moves to the next step and not the previous step

 



we will discuss about the Literal control. In my opinion this is the least understood control in asp.net.

Topics Discussed
a) Literal control in asp.net
b) Difference between a literal control and label control



1. In many ways a Literal control is similar to a Label control. Both of these controls are used to display Text on a webform. The Text property can be set in the HTML or in the code-behind.

2. Label control wraps the text in a span tag when rendered. Any style that is applied to the Label control, will be rendered using the style property of the span tag.

For example, the following HTML
<asp:Label ID="Label1" runat="server"  Text="Lable Text"
ForeColor="Red" Font-Bold="true" ></asp:Label>

Will be rendered as
<span id="Label1" style="color:Red;font-weight:bold;">Lable Text</span>



3. A literal control, doesn't output any surrounding tags. The Text is displayed as is.
For example, the following HTML
<asp:Literal ID="Literal1" runat="server"
Text="Literal Control Text"></asp:Literal>

will be rendered as
Literal Control Text

4. If you want to apply any styles to a literal control, include them in the Text of the literal control. For example, the following HTML sets the font to red color and bold.
<asp:Literal ID="Literal1" runat="server"
Text="<b><font color='Red'>Literal Control Text</font></b>">
</asp:Literal>

The above HTML will be rendered as
<b><font color='Red'>Literal Control Text</font></b>

5. So, if you just want the text to be displayed without any styles, then use Literal control, else use Label control.

6. By default, both the Label and Literal Control's does not encode the text they display. For example, the following HTML displays a javascript alert 
<asp:Label ID="Label" runat="server"
Text="<script>alert('Lable Text');</script>">
</asp:Label>
<br />
<asp:Literal ID="Literal1" runat="server"
Text="<script>alert('Literal Text');</script>">
</asp:Literal>

and will be rendered as
<span id="Label"><script>alert('Lable Text');</script></span>
<br />
<script>alert('Literal Text');</script>

7. To HTML encode the Label Text, Server.HtmlEncode() method can be used, and for Literal control, Mode property can be used.
<asp:Label ID="Label1" runat="server">
<%=Server.HtmlEncode("<script>alert('Lable Text');</script>")%>
</asp:Label>
<br />
<asp:Literal ID="Literal1" runat="server"
Text="<script>alert('Literal Text');</script>"
Mode="Encode"></asp:Literal>

The above HTML will be rendered as
<span id="Label1">&lt;script&gt;alert(&#39;Lable Text&#39;);&lt;/script&gt;</span>
<br />
&lt;script&gt;alert(&#39;Literal Text&#39;);&lt;/script&gt;

8. Literal control is a light weight control, when compared with the Label control.

9. The inheritance hierarchy for Literal control class is (Object => Control => Literal), where as for the Lable control, the hierarchy is (Object => Control => WebControl=> Label)

https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgvz8aS4R7cZuP_-xrol6VM3A3czbK4Reooqyxc1g_PhBV8vqMhnZQ9jA_J0TKepYeuE4TDACdSO7HYq0o4eHMhBQ_ZWrSru-zrs8SjtBoDI03O49w8DOPJPNr4pXoZVGSyhR7O8a3Jy-37/s1600/Difference+between+Label+and+Literal+controls+in+asp.net.png

The panel control is used as a container for other controls. A panel control is very handy, when you want to group controls, and then show or hide, all the controls in the group. Panel control, is also very useful, when adding controls to the webform dynamically. We will discuss about, adding controls dynamically using panel control in the next video session.

In this video, we will discuss about, using the Panel control to group controls, and then toggle their visibility, using the Panel control's Visible property.

The following webform is used by both, an Admin and Non-Admin user. When the Admin user is selected from the dropdownlist, we want to show the controls that are relevant to the Admin user. When the Non-Admin user is selected, only the Non-Admin specific content and controls should be shown.



HTML of the ASPX page. At the moment we are not using Panel control.
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
            onselectedindexchanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem Text="Select User" Value="-1"></asp:ListItem>
    <asp:ListItem Text="Admin" Value="Admin"></asp:ListItem>
    <asp:ListItem Text="Non-Admin" Value="Non-Admin"></asp:ListItem>
</asp:DropDownList>
<table>
    <tr>
        <td colspan="2">
            <asp:Label ID="AdminGreeting" runat="server" Font-Size="XX-Large"
            Text="You are logged in as an administrator">
            </asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="AdminNameLabel" runat="server" Text="Admin Name:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="AdminNameTextBox" runat="server" Text="Tom">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="AdminRegionLabel" runat="server" Text="Admin Region:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="AdminRegionTextBox" runat="server" Text="Asia">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="AdminActionsLabel" runat="server" Text="Actions:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="AdminActionsTextBox" runat="server" Font-Size="Medium" TextMode="MultiLine"
               
                Text="There are 4 user queries to be answered by the end of Dcemeber 25th 2013."
                Font-Bold="True" ></asp:TextBox>
        </td>
    </tr>
</table>
<table>
    <tr>
        <td colspan="2">
            <asp:Label ID="NonAdminGreeting" runat="server" Font-Size="XX-Large"
            Text="Welcome Tom!">
            </asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="NonAdminNameLabel" runat="server" Text="User Name:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="NonAdminNameTextBox" runat="server" Text="Mike">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="NonAdminRegionLabel" runat="server" Text="User Region:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="NonAdminRegionTextBox" runat="server" Text="United Kingdom">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="NonAdminCityLabel" runat="server" Text="City:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="NonAdminCityTextBox" runat="server" Text="London">
            </asp:TextBox>
        </td>
    </tr>
</table>



Code-Behind code. Since we are not using the panel control, each control's visible property need to be changed depending on the selection in the dropdownlist.
protected void Page_Load(object sender, EventArgs e)
{
   
// When the page first loads, hide all admin and non admin controls
   
if (!IsPostBack)
    {
        HideAdminControls();
        HideNonAdminControls();
    }
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
   
if (DropDownList1.SelectedValue == "Admin")
    {
        ShowAdminControls();
        HideNonAdminControls();
    }
   
else if (DropDownList1.SelectedValue == "Non-Admin")
    {
        ShowNonAdminControls();
        HideAdminControls();
    }
   
else
    {
        HideAdminControls();
        HideNonAdminControls();
    }
}

private void HideAdminControls()
{
    AdminGreeting.Visible =
false;
    AdminNameLabel.Visible = 
false;
    AdminNameTextBox.Visible = 
false;
    AdminRegionLabel.Visible = 
false;
    AdminRegionTextBox.Visible = 
false;
    AdminActionsLabel.Visible = 
false;
    AdminActionsTextBox.Visible = 
false;
}
private void ShowAdminControls()
{
    AdminGreeting.Visible =
true;
    AdminNameLabel.Visible = 
true;
    AdminNameTextBox.Visible = 
true;
    AdminRegionLabel.Visible = 
true;
    AdminRegionTextBox.Visible = 
true;
    AdminActionsLabel.Visible = 
true;
    AdminActionsTextBox.Visible = 
true;
}
private void HideNonAdminControls()
{
    NonAdminGreeting.Visible = 
false;
    NonAdminNameLabel.Visible = 
false;
    NonAdminNameTextBox.Visible = 
false;
    NonAdminRegionLabel.Visible = 
false;
    NonAdminRegionTextBox.Visible = 
false;
    NonAdminCityLabel.Visible = 
false;
    NonAdminCityTextBox.Visible = 
false;
}
private void ShowNonAdminControls()
{
    NonAdminGreeting.Visible = 
true;
    NonAdminNameLabel.Visible = 
true;
    NonAdminNameTextBox.Visible = 
true;
    NonAdminRegionLabel.Visible = 
true;
    NonAdminRegionTextBox.Visible = 
true;
    NonAdminCityLabel.Visible = 
true;
    NonAdminCityTextBox.Visible = 
true;
}

HTML of the ASPX page. The panel control is used to group the controls.
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true"
            onselectedindexchanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem Text="Select User" Value="-1"></asp:ListItem>
    <asp:ListItem Text="Admin" Value="Admin"></asp:ListItem>
    <asp:ListItem Text="Non-Admin" Value="Non-Admin"></asp:ListItem>
</asp:DropDownList>
<asp:Panel ID="AdminPanel" runat="server">
<table>
    <tr>
        <td colspan="2">
            <asp:Label ID="AdminGreeting" runat="server" Font-Size="XX-Large"
            Text="You are logged in as an administrator">
            </asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="AdminNameLabel" runat="server" Text="Admin Name:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="AdminNameTextBox" runat="server" Text="Tom">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="AdminRegionLabel" runat="server" Text="Admin Region:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="AdminRegionTextBox" runat="server" Text="Asia">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="AdminActionsLabel" runat="server" Text="Actions:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="AdminActionsTextBox" runat="server" Font-Size="Medium" TextMode="MultiLine"
               
                Text="There are 4 user queries to be answered by the end of Dcemeber 25th 2013."
                Font-Bold="True" ></asp:TextBox>
        </td>
    </tr>
</table>
</asp:Panel>
<asp:Panel ID="NonAdminPanel" runat="server">
<table>
    <tr>
        <td colspan="2">
            <asp:Label ID="NonAdminGreeting" runat="server" Font-Size="XX-Large"
            Text="Welcome Tom!">
            </asp:Label>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="NonAdminNameLabel" runat="server" Text="User Name:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="NonAdminNameTextBox" runat="server" Text="Mike">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="NonAdminRegionLabel" runat="server" Text="User Region:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="NonAdminRegionTextBox" runat="server" Text="United Kingdom">
            </asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <asp:Label ID="NonAdminCityLabel" runat="server" Text="City:">
            </asp:Label>
        </td>
        <td>
            <asp:TextBox ID="NonAdminCityTextBox" runat="server" Text="London">
            </asp:TextBox>
        </td>
    </tr>
</table>
</asp:Panel>

Code-Behind code: 
protected void Page_Load(object sender, EventArgs e)
{
   
// When the page first loads, hide admin and non admin panels
   
if (!IsPostBack)
    {
        AdminPanel.Visible =
false;
        NonAdminPanel.Visible =
false;
    }
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
   
if (DropDownList1.SelectedValue == "Admin")
    {
        AdminPanel.Visible =
true;
        NonAdminPanel.Visible =
false;
    }
   
else if (DropDownList1.SelectedValue == "Non-Admin")
    {
        AdminPanel.Visible =
false;
        NonAdminPanel.Visible =
true;
    }
   
else
    {
        AdminPanel.Visible =
false;
        NonAdminPanel.Visible =
false;
    }
}

The panel control is used as a container for other controls. A panel control is very handy, when you want to group controls, and then show or hide, all the controls in the group. We have seen how to do this in Part 42, of this video series.

Panel control, is also very useful, when adding controls to the webform dynamically. We will discuss this in this session.



https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9ehTMpELJ2fd1qQ2ey7GLHhu5FPI_9Xk09ILGtBuBxXPU9bK45lzaUVJp6L78QFz8jXfviw5fW1NcpThgYbIFOYwm4PeBe6m6_CCP6LLbQNUNBdZwKKe7jMk4OBZr2_izheUTqhH2knmb/s1600/Generating+controls+dynamically+using+panel+control.png



HTML of the ASPX page
<div style="font-family: Arial">
    <table>
    <tr>
        <td><b>Control Type</b></td>
        <td>
            <asp:CheckBoxList ID="chkBoxListControlType" runat="server" RepeatDirection="Horizontal">
                <asp:ListItem Text="Label" Value="Label"></asp:ListItem>
                <asp:ListItem Text="TextBox" Value="TextBox"></asp:ListItem>
                <asp:ListItem Text="Button" Value="Button"></asp:ListItem>
            </asp:CheckBoxList>
        </td>
        <td><b>How Many</b></td>
        <td>
            <asp:TextBox ID="txtControlsCount" runat="server" Width="40px"></asp:TextBox>
        </td>
        <td>
            <asp:Button ID="btnGenerateControl" runat="server" Text="Generate Controls"
                onclick="btnGenerateControl_Click" />
        </td>
    </tr>
    <tr>
        <td colspan="5">
            <h3>Label Controls</h3>
        </td>
    </tr>
    <tr>
        <td colspan="5" id="tdLabels" runat="server">
            <asp:Panel ID="pnlLabels" runat="server">
            </asp:Panel>
            <%--<asp:PlaceHolder ID="phLabels" runat="server">
            </asp:PlaceHolder>--%>
        </td>
    </tr>
    <tr>
        <td colspan="5">
            <h3>TextBox Controls</h3>
        </td>
    </tr>
    <tr>
        <td colspan="5" id="tdTextBoxes" runat="server">
            <asp:Panel ID="pnlTextBoxes" runat="server">
            </asp:Panel>
            <%--<asp:PlaceHolder ID="phTextBoxes" runat="server">
            </asp:PlaceHolder>--%>
        </td>
    </tr>
    <tr>
        <td colspan="5">
            <h3>Button Controls</h3>
        </td>
    </tr>
    <tr>
        <td colspan="5" id="tdButtons" runat="server">
            <asp:Panel ID="pnlButtons" runat="server">
            </asp:Panel>
            <%--<asp:PlaceHolder ID="phButtons" runat="server">
            </asp:PlaceHolder>--%>
        </td>
    </tr>
    </table>      
</div>

Code-Behind Code:
protected void btnGenerateControl_Click(object sender, EventArgs e)
{
   
// Retrieve the count of the controls to generate
   
int Count = Convert.ToInt16(txtControlsCount.Text);
   
// Loop thru each list item in the CheckBoxList
   
foreach (ListItem li in chkBoxListControlType.Items)
    {
       
if (li.Selected)
        {
           
// Generate Lable Controls
           
if (li.Value == "Label")
            {
               
for (int i = 1; i <= Count; i++)
                {
                   
Label lbl = new Label();
                    lbl.Text =
"Label - " + i.ToString();
                   
//phLabels.Controls.Add(lbl);
                    //tdLabels.Controls.Add(lbl);
                    pnlLabels.Controls.Add(lbl);
                }
            }
           
// Generate TextBox controls
           
else if (li.Value == "TextBox")
            {
               
for (int i = 1; i <= Count; i++)
                {
                   
TextBox txtBox = new TextBox();
                    txtBox.Text =
"TextBox - " + i.ToString();
                   
//phTextBoxes.Controls.Add(txtBox);
                    //tdTextBoxes.Controls.Add(txtBox);
                    pnlTextBoxes.Controls.Add(txtBox);
                }
            }
           
// Generate Button Controls
           
else
            {
               
for (int i = 1; i <= Count; i++)
                {
                   
Button btn = new Button();
                    btn.Text =
"Button - " + i.ToString();
                   
//phButtons.Controls.Add(btn);
                    //tdButtons.Controls.Add(btn);
                    pnlButtons.Controls.Add(btn);
                }
            }
        }
    }
}

Suggested Videos
Part 41 - Literal control in asp.net
Part 42 - Asp.net panel control
Part 43 - Creating controls dynamically using asp.net panel control

Validation controls are used to ensure if, the data, entered by the user is valid. Microsoft asp.net framework, provides 6 built-in validation controls.
1. RequiredFieldValidator
2. RangeValidator
3. RegularExpressionValidator
4. CompareValidator
5. CustomValidator  
6. ValidationSummary

RequiredField validator control in asp.net



These validation controls can be used to perform both client side and server side validation.

Browser's understand only client scripts and HTML. In the past to perform client side validation, developers had to write themselves the required javascript code. With validation controls, we don't have to write javascript, we can use the built-in validation controls, which will generate the required javascript for us.

Client scripts can spread viruses and cause security concerns. Because of this, users may disable JavaScript on their browser. If this happens, client side validation is skipped. That is why, it is always a good practice to have server side validation as well.

The validation control's also perform server side validation. Server side validation is always performed, irrespective of whether the client side validation is done or not.

In this video we will discuss about RequiredField validator control. This control, ensures that the required field is entered by the user. Let us understand with an example.



RequiredField validator control in asp.net

Consider the HTML below. TextBox with ID="txtName" expects the user to enter their name. This is required field. Next to this textbox is a RequiredFieldValidator control, which is used to ensure that the user has entered his name. ControlToValidate property specifies the control to validate. ErrorMessage is the message that is displayed when the validation fails. To validate ddlGender DropDownList, we have RequiredFieldValidatorGender. We have specified InitialValue="-1". This will ensure that, if the user has selected, "Select Gender" option from the DropDownList, the control will still fail the validation.
<table>
    <tr>
        <td>
            <b>Name</b>
        </td>
        <td>
            :<asp:TextBox ID="txtName" runat="server" Width="150px">
            </asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorName" runat="server"
            ErrorMessage="Name is required" ForeColor="Red"
            ControlToValidate="txtName" Display="Dynamic" >
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            <b>Gender</b>
        </td>
        <td>
            :<asp:DropDownList ID="ddlGender" runat="server" Width="150px">
                <asp:ListItem Text="Select Gender" Value="-1"></asp:ListItem>
                <asp:ListItem Text="Male" Value="Male"></asp:ListItem>
                <asp:ListItem Text="Female" Value="Female"></asp:ListItem>
            </asp:DropDownList>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorGender" runat="server"
            ErrorMessage="Gender is required" ForeColor="Red" InitialValue="-1"
            ControlToValidate="ddlGender" Display="Dynamic" >
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Button ID="btnSave" runat="server" Text="Save" Width="100px"
                onclick="btnSave_Click"/>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblStatus" runat="server" Font-Bold="true">
            </asp:Label>
        </td>
    </tr>
</table>

Code-Behind code: Page.IsValid is a read-only property. This property returns true if all the validation controls has passed validation. Use this property to perform server side validation.
protected void btnSave_Click(object sender, EventArgs e)
{
           
   
if (Page.IsValid)
    {
        lblStatus.ForeColor = System.Drawing.
Color.Green;
        lblStatus.Text =
"Data saved successfully!";
    }
    else
    {
        lblStatus.ForeColor = System.Drawing.
Color.Red;
        lblStatus.Text =
"Data not valid and not saved!";
    }
}

Run the project, and notice that the client side validation is performed. Now, disable Javascript. To disable javascript in, internet explorer
1. Click on Tools on the Menu Bar. If the Menu bar is not visible, press ALT+T.
2. From the Tools menu, select Internet Options
3. Click on the Security tab, on the internet options window
4. Select Local Intranet icon and click on Cutom Level button
5. Scroll down in the Security Settings window, and find Scripting option in the list.
6. Click Disable radiobutton under active scripting
7. Click OK and click Yes on the warning.

The above steps should disable javascript. Run the project now, and click Save button, without entering any data. Notice, that the client side validation is skipped, but the server side validation is performed.

Rangevalidator control in asp.net - Part 45

Suggested Videos
Part 42 - Asp.net panel control
Part 43 - Creating controls dynamically using asp.net panel control
Part 44 - RequiredField validator control in asp.net

In this video we will discuss about Rangevalidator control. This control is used to check if the value is within a specified range of values. For example, Rangevalidator can be used to check if the age falls between 1 and 100.

RangeValidator control in asp.net

In the HTML below, TextBox txtAge captures age of the person. If the user enter's any number that is not between 1 & 100 the
validation fails. The minimum and maximum value for the age is specified by MinimumValue and MaximumValue properties. Since, age is an integer, the Type is specified as integer.
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
    ErrorMessage="Age must be between 1 & 100"
    MinimumValue="1" MaximumValue="100"
    ControlToValidate="txtAge" Type="Integer" >
</asp:RangeValidator>



Properties specific to Rangevalidator control:
Type - This property, specifies the data type of the value to check. Data types supported include - Currency, Date, Double, Integer, String.
MinimumValue - The minimum value allowed
MaximumValue - The maximum value allowed

Comple HTML of the aspx page used in the Demo: Rangevalidator only checks if the entered data is within the allowed range. If you want to check for a required field, use RequiredFieldValidator. For the age field, we are using both RequiredFieldValidator and RangeValidator. Also notice that, in this example we are using the Display property. If the Display property is not set, or, if it is set to static, then the error message will be rendered, with style visibility:hidden. Because of this, the error message will always occupy the space on the screen even if the validation passes. This pushes
"Age is Required" error message to the right. To correct this we have set Display="Dynamic". This renders the error message with style display:none. If a tag has this style, it will not occupy space when not visible.
<table>
    <tr>
        <td>
            <b>Age</b>
        </td>
        <td>
            :<asp:TextBox ID="txtAge" runat="server" Width="150px">
                </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorAge" runat="server"
                ErrorMessage="Age must be between 1 & 100"
                MinimumValue="1" MaximumValue="100"
                ControlToValidate="txtAge" Type="Integer"
                ForeColor="Red" Display="Dynamic">
            </asp:RangeValidator>
            <asp:RequiredFieldValidator ID="RequiredFieldValidatorAge"
            runat="server" ErrorMessage="Age is required"
            ControlToValidate="txtAge" ForeColor="Red"
            Display="Dynamic" >
            </asp:RequiredFieldValidator>
        </td>
    </tr>
    <tr>
        <td>
            <b>Date Available</b>
        </td>
        <td>
            :<asp:TextBox ID="txtDateAvailable" runat="server" Width="150px">
            </asp:TextBox>
            <asp:RangeValidator ID="RangeValidatorDateAvailable" runat="server"
                ErrorMessage="Date must be between 01/01/2012 & 31/12/2012"
                MinimumValue="01/01/2012" MaximumValue="31/12/2012"
                ControlToValidate="txtDateAvailable" Type="Date"
                ForeColor="Red">
            </asp:RangeValidator>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Button ID="btnSave" runat="server" Text="Save" Width="100px"
                onclick="btnSave_Click" />
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <asp:Label ID="lblStatus" runat="server" Font-Bold="true">
            </asp:Label>
        </td>
    </tr>
</table>



Code-Behind page code:
protected void btnSave_Click(object sender, EventArgs e)
{
   
if (Page.IsValid)
    {
        lblStatus.ForeColor = System.Drawing.
Color.Green;
        lblStatus.Text =
"Data Saved successfully";
    }
   
else
    {
        lblStatus.ForeColor = System.Drawing.
Color.Red;
        lblStatus.Text =
"Validation Failed! Data not saved";
    }
}

Display property is supported by all validation controls.
None - Error message not rendered and displayed next to the control. Used to show the error message only in the ValidationSummary control
Static - The error message is displayed next to the control if validation fails. Space is reserved on the page for the message even if validation succeeds. The span tag is rendered with style visibility:hidden
Dynamic - The error message is displayed next to the control if validation fails. Space is not reserved on the page for the message if the validation succeeds. The span tag is rendered with style display:none.

CompareValidator control in asp.net

CompareValidator control is used to compare the value of one control with the value of another control or a constant value. The comparison operation can be any of the following.
1. Equal
2. GreaterThan
3. GreaterThanEqual
4. LessThan
5. LessThanEqual
6. NotEqual
7. DataTypeCheck

CompareValidator control in asp.net



CompareValidator can also be used for DataType checking.

The following are the properties that are specific to the compare validator
1. ControlToCompare - The control with which to compare
2. Type - The DataType of the value to compare. String, Integer etc.
3. Operator = The comparison operator. Equal, NotEqual etc.
4. ValueToCompare - The constant value to compare with.

SetFocusOnError property is supported by all validation controls. If this property is set to true, then the control will automatically receive focus, when the validation fails.



Using CompareValidator to compare the value of one control with the value of another control.
<table>
    <tr>
        <td>
            <b>Password</b>
        </td>
        <td>
            :<asp:TextBox ID="txtPassword" runat="server" Width="150px" TextMode="Password"></asp:TextBox>
        </td>
    </tr>
    <tr>
        <td>
            <strong>Retype Password</strong></td>
        <td>
            :<asp:TextBox ID="txtRetypePassword" runat="server"
                Width="150px" TextMode="Password"></asp:TextBox>
            <asp:CompareValidator ID="CompareValidatorPassword" runat="server"
            ErrorMessage="Password and Retype Password must match"
            ControlToValidate="txtRetypePassword" ControlToCompare="txtPassword"
            Type="String" Operator="Equal" ForeColor="Red">
            </asp:CompareValidator>
        </td>
    </tr>
</table>

Using CompareValidator to compare the value of one control with a constant value.
<asp:TextBox ID="txtDateofapplication" runat="server" Width="150px">
</asp:TextBox>
<asp:CompareValidator ID="CompareValidatorDateofbirth" runat="server"
ErrorMessage="Date of application must be greater than 01/01/2012"
ControlToValidate="txtDateofapplication" ValueToCompare="01/01/2012"
Type="Date" Operator="GreaterThan" ForeColor="Red"
SetFocusOnError="true"></asp:CompareValidator>

Using CompareValidator to check DataType
<asp:TextBox ID="txtAge" runat="server" Width="150px"></asp:TextBox>
<asp:CompareValidator ID="CompareValidatorAge" runat="server"
ErrorMessage="Age must be a number" ControlToValidate="txtAge"
Operator="DataTypeCheck" Type="Integer" ForeColor="Red"
SetFocusOnError="true"></asp:CompareValidator>

RegularExpressionValidator control in asp.net


This is a very powerful validation control. This control is used to check if the value of an associated input control matches the pattern specified by a regular expression. The only property that is specific to the RegularExpressionValidator is ValidationExpression.

RegularExpressionValidator control in asp.net



This example, checks if the input mataches the pattern of an email address
<asp:TextBox ID="txtEmail" runat="server" Width="150px">
</asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail" runat="server"
ControlToValidate="txtEmail" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
ErrorMessage="Invalid Email" ForeColor="Red"></asp:RegularExpressionValidator>



By default client side validation is turned on. To disable client side validation set EnableClientScript o false. This property is supported by all validation controls.

To disable validation control set Enabled propety to false.

CustomValidator control in asp.net

CustomValidator control in asp.net

CustomValidator control allows us to write a method with a custom logic to handle the validation of the value entered. If none of the other validation controls, serve our purpose, then the CustomValidator can be used.



Just like any other validation control, CustomValidator can be used for both client and server side validation. Client side and server side validation functions, needs to be written by the developer, and associate them to the custom validator control.

The following are the properties that are specific to the CustomValidator control
ClientValidationFunction - Specifies the name of the client side validation method.
ValidateEmptyText - Specifies whether the validator validates the control, when the text of the control is empty. By default this property is false, and both the client side and server side validation functions will not be invoked, if the associated input control is empty.

Events specific to the CustomValidator control
OnServerValidate - Specifies the name of the server side validation method.



HTML of the aspx page: This example checks if the entered number is even. ValidateEmptyText property of the CustomValidator control, is set to true. So the validation is also triggered when the textbox is empty.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script language="javascript" type="text/javascript">
        // Client side validation function to check if the number is even.
        function IsEven(source, args)
        {
            if (args.Value == "")
            {
                args.IsValid = false;
            }
            else
            {
                if (args.Value % 2 == 0)
                {
                    args.IsValid = true;
                }
                else
                {
                    args.IsValid = false;
                }
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="font-family: Arial">
        <table>
            <tr>
                <td>
                    <b>Please enter a positive even number</b>
                </td>
                <td>
                    <asp:TextBox ID="txtEvenNumber" runat="server"></asp:TextBox>
                    <asp:CustomValidator ID="CustomValidatorEvenNumber" runat="server"
                        ForeColor="Red"
                        ErrorMessage="Not an even number"
                        OnServerValidate="CustomValidatorEvenNumber_ServerValidate"
                        ControlToValidate="txtEvenNumber"
                        ClientValidationFunction="IsEven"
                        ValidateEmptyText="true">
                    </asp:CustomValidator>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Button ID="btnSubmit" runat="server" Text="Save"
                        onclick="btnSubmit_Click" />
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Label ID="lblStatus" runat="server" Font-Bold="true"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Code-Behind page code: Set EnableClientScript to true, to test the server side validation method.
protected void btnSubmit_Click(object sender, EventArgs e)
{
   
if (Page.IsValid)
    {
        lblStatus.Text =
"Data Saved";
        lblStatus.ForeColor = System.Drawing.
Color.Green;
    }
   
else
    {
        lblStatus.Text =
"Validation Error! Data Not Saved";
        lblStatus.ForeColor = System.Drawing.
Color.Red;
    }
}

protected void CustomValidatorEvenNumber_ServerValidate(object source, ServerValidateEventArgs args)
{
   
if (args.Value == "")
    {
        args.IsValid =
false;
    }
   
else
    {
       
int Number;
       
bool isNumber = int.TryParse(args.Value, out Number);
       
if (isNumber && Number >= 0 && (Number % 2) == 0)
        {
            args.IsValid =
true;
        }
       
else
        {
            args.IsValid =
false;
        }
    }
}

ValidationSummary control in asp.net


ValidationSummary control is used to display a summary of all validation errors occurred in a Web page, at one place. In general, in a real time applications, it is very common to display a red star symbol next to the input control where the error occurred, and then the detailed error message in the validation summary control as shown below.

ValidationSummary control example in asp.net



Properties specific to the validation summary control:
HeaderText - The header text for the validation summary control
ShowSummary - Whether to display the summary text of all the validation errors
ShowMessageBox - Whether to display a message box with all the validation errors
DisplayMode - Display format for the summary.

DisplayMode can be List, BulletList, SingleParagraph



HTML of the ASPX Page:
<div style="font-family: Arial">
    <table style="border: 1px solid black">
        <tr>
            <td colspan="2">
                <h2>User Registration</h2>
            </td>
        </tr>
        <tr>
            <td>
                <b>Email</b>
            </td>
            <td>
                <asp:TextBox ID="txtEmail" runat="server" Width="100px">
                </asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail"
                runat="server" ForeColor="Red"
                ErrorMessage="Email is required"
                ControlToValidate="txtEmail" Display="Dynamic" Text="*">
                </asp:RequiredFieldValidator>
                <asp:RegularExpressionValidator ID="RegularExpressionValidatorEmail"
                runat="server" ErrorMessage="Invalid Email Format"
                ControlToValidate="txtEmail" ForeColor="Red"
                ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                Text="*">
                </asp:RegularExpressionValidator>
            </td>
        </tr>
        <tr>
            <td>
                <b>User Name</b>
            </td>
            <td>
                <asp:TextBox ID="txtUserName" runat="server" Width="100px">
                </asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidatorUserName"
                runat="server" ForeColor="Red"
                ErrorMessage="Username is required"
                ControlToValidate="txtUserName" Display="Dynamic" Text="*">
                </asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td>
                <b>Password</b>
            </td>
            <td>
                <asp:TextBox ID="txtPassword" runat="server" Width="100px"
                TextMode="Password"></asp:TextBox>
                <asp:RequiredFieldValidator ID="RequiredFieldValidatorPassword"
                runat="server" ForeColor="Red"
                ErrorMessage="Password is required"
                ControlToValidate="txtPassword" Display="Dynamic" Text="*">
                </asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td>
                <b>Confirm Password</b>
            </td>
            <td>
                <asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password"
                Width="100px"></asp:TextBox>
                <asp:CompareValidator ID="CompareValidatorPassword" runat="server"
                ErrorMessage="Password and Confirm Password must match"
                ControlToValidate="txtConfirmPassword" ControlToCompare="txtPassword"
                Operator="Equal" Type="String" ForeColor="Red" Text="*">
                </asp:CompareValidator>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Button ID="btnSubmit" runat="server" Text="Save"
                    onclick="btnSubmit_Click" />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:ValidationSummary ID="ValidationSummary1" runat="server"
                ForeColor="Red" HeaderText="Page Errors" ShowMessageBox="True"
                ShowSummary="true" DisplayMode="List"
                />
            </td>
        </tr>
        <tr>
            <td colspan="2">
                <asp:Label ID="lblStatus" runat="server" Font-Bold="true"></asp:Label>
            </td>
        </tr>
    </table>
</div>

ValidationGroups in asp.net
we will discuss about ValidationGroups and CausesValidation.

Consider the image below. 
https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjC5Q3maJy_SZu1VDskrXzgeKzVHBoakRKlG7iOOB-b8bNO79GRHCPV-Evn09-feHWXNKn_Um5x2OnjxLttDkX4osOiRdgEwq24ZLtrHr_ktpDyKeLingS4ctQ_nEsJGqIOBvjrp5RAJM89/s1600/ValidationGroups+in+asp.net.png

The first problem here is that, when I click the Clear button, Form validation still happens. When I click the clear button, I just want to clear the textboxes in the Registration section. Validations doesn't make any sense here.
So, how do I prevent validation from happening? 
Just, set the CausesValidation property of the button control to false. 



The second problem, is that when I click the Login button, only fields in the Login section(UserName and Password) needs to be validated. Along the same lines when I click the "Register" button, only fields in the Registration section(Email, UserName, Password and ConfirmPassword) needs to validated. If we don't use validation groups, then by default, whenever, you click a button, all the validation controls on the page get validated.

So, when you click the login button, and if you want only, the fields in the Login section(UserName and Password) to be validated, then set, the ValidationGroup property of the validation controls and the login button control to the same group name. Use a different group name for the validation controls and register button, in the registration section.



HTML of the aspx page:
<div style="font-family: Arial">
<table>
    <tr>
        <td style="vertical-align: top">
            <table style="border: 1px solid black">
                <tr>
                    <td colspan="2">
                        <h2>
                            Login</h2>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>User Name</b>
                    </td>
                    <td>
                        <asp:TextBox ID="txtUN" runat="server" Width="100px">
                        </asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorUN"
                            runat="server" ForeColor="Red"
                            ErrorMessage="Username is required"
                            ControlToValidate="txtUN" Display="Dynamic"
                            Text="*" ValidationGroup="Login">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Password</b>
                    </td>
                    <td>
                        <asp:TextBox ID="TextBoxPWD" runat="server" Width="100px"
                        TextMode="Password"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorPWD"
                            runat="server" ForeColor="Red"
                            ErrorMessage="Password is required"
                            ControlToValidate="TextBoxPWD" Display="Dynamic"
                            Text="*" ValidationGroup="Login">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Button ID="btnLogin" ValidationGroup="Login"
                        runat="server" Text="Login"
                        onclick="btnLogin_Click" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:ValidationSummary ValidationGroup="Login"
                            ID="ValidationSummary2" runat="server"
                            ForeColor="Red" HeaderText="Page Errors"
                            ShowMessageBox="True" ShowSummary="true"
                            DisplayMode="List" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Label ID="lblLoginStatus" runat="server"
                        Font-Bold="true"></asp:Label>
                    </td>
                </tr>
            </table>
        </td>
        <td>
            &nbsp;&nbsp;
        </td>
        <td>
            <table style="border: 1px solid black">
                <tr>
                    <td colspan="2">
                        <h2>
                            User Registration</h2>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Email</b>
                    </td>
                    <td>
                        <asp:TextBox ID="txtEmail" runat="server" Width="100px">
                        </asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorEmail"
                            runat="server" ForeColor="Red"
                            ErrorMessage="Email is required"
                            ControlToValidate="txtEmail" Display="Dynamic"
                            Text="*" ValidationGroup="Registration">
                        </asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator
                            ID="RegularExpressionValidatorEmail"
                            runat="server"
                            ErrorMessage="Invalid Email Format"
                            ControlToValidate="txtEmail" ForeColor="Red"
                            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                            Text="*"
                            ValidationGroup="Registration">
                        </asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>User Name</b>
                    </td>
                    <td>
                        <asp:TextBox ID="txtUserName" runat="server" Width="100px">
                        </asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorUserName"
                            runat="server" ForeColor="Red"
                            ErrorMessage="Username is required"
                            ControlToValidate="txtUserName" Display="Dynamic"
                            Text="*" ValidationGroup="Registration">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Password</b>
                    </td>
                    <td>
                        <asp:TextBox ID="txtPassword" runat="server"
                        Width="100px" TextMode="Password"></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidatorPassword"
                            runat="server" ForeColor="Red"
                            ErrorMessage="Password is required"
                            ControlToValidate="txtPassword" Display="Dynamic"
                            Text="*" ValidationGroup="Registration">
                        </asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Confirm Password</b>
                    </td>
                    <td>
                        <asp:TextBox ID="txtConfirmPassword" runat="server"
                            TextMode="Password" Width="100px"></asp:TextBox>
                        <asp:CompareValidator ID="CompareValidatorPassword"
                            runat="server"
                            ErrorMessage="Password and Confirm Password must match"
                            ControlToValidate="txtConfirmPassword"
                            ControlToCompare="txtPassword" Operator="Equal"
                            Type="String" ForeColor="Red" Text="*"
                            ValidationGroup="Registration">
                        </asp:CompareValidator>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Button ID="btnSubmit" runat="server" Text="Register"
                        OnClick="btnSubmit_Click" ValidationGroup="Registration"/>
                        &nbsp;
                        <asp:Button ID="btnClear" runat="server" onclick="btnClear_Click"
                        CausesValidation="false" Text="Clear" />
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:ValidationSummary ID="ValidationSummary1" runat="server"
                            ForeColor="Red" HeaderText="Page Errors" ShowMessageBox="True"
                            ShowSummary="true" DisplayMode="List"
                            ValidationGroup="Registration"/>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:Label ID="lblStatus" runat="server"
                        Font-Bold="true"></asp:Label>
                    </td>
                </tr>
            </table>
        </td>
    </tr>
</table>
</div>

Code-Behind:
protected void btnSubmit_Click(object sender, EventArgs e)
{
   
if (Page.IsValid)
    {
        lblStatus.Text =
"No registration validation Errors";
        lblStatus.ForeColor = System.Drawing.
Color.Green;
    }
   
else
    {
        lblStatus.Text =
"Registration validation Errors";
        lblStatus.ForeColor = System.Drawing.
Color.Red;
    }
}

protected void btnClear_Click(object sender, EventArgs e)
{
    txtEmail.Text = "";
    txtUserName.Text = "";
    txtPassword.Text = "";
    txtConfirmPassword.Text = "";
}

protected void btnLogin_Click(object sender, EventArgs e)
{
   
if (Page.IsValid)
    {
        lblLoginStatus.Text =
"No Login Validation Errors";
        lblStatus.ForeColor = System.Drawing.
Color.Green;
    }
   
else
    {
        lblStatus.Text =
"Login validation errors";
        lblStatus.ForeColor = System.Drawing.
Color.Red;
    }
}

No comments:

Post a Comment