Sponsored Ad

Friday, December 17, 2010

How to Execute Next Statement After Error in C#

This Code will help to to bypass error and execute all other statements. For example in this scenario we have two statements. one is before error and another is after error. In normal case if any error occurs the control will not execute the next statements after errors. While if we use the try catch block and suppress the error then it will execute the next statements also. 

You can also handle the error in exception block as per your requirement.

How to Execute Next Statement After Error in C#

Code to Bypass Error and Execute Next Statement:

using System;

namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Satement Before Error.");
            try
            {
                int i = Convert.ToInt16("Str");
            }
            catch (Exception ex)
            { }
            Console.WriteLine("Satement After Error.");
            Console.ReadLine();
        }    
    }
}

Friday, September 24, 2010

While Loop Program Using C# | While Loop Example

This simple program demonstrate the use of while loop in C#. While loop run until condition reaches to false.

image

Code for While Loop:

using System;
using System.Text;
using System.Data;
namespace Console_App
{
    public class clsWhileLoop
    {
        public static void Main()
        {
            try
            {
                Console.WriteLine("Enter a number:");
                int GivenNumber = Convert.ToInt16(Console.ReadLine());
                while (GivenNumber < 10)
                {
                    Console.WriteLine("Loop Count {0} ", GivenNumber);
                    GivenNumber++;
                }
            }
            catch (Exception ex)
            {
                //handle exception here
            }
            Console.ReadLine();
        }
    }
}

How to use If Else in C# | If Else Example using C#

 

This is program of If Else complex and simple examples. This example shows the exact use of If Else statement in C#.

How to use If Else in C# | If Else Example using C#

Source Code of If Else Example:

using System;
using System.Text;
using System.Data;
namespace Console_App
{
    public class clsIfElase
    {
        public static void Main()
        {
            try
            {            
                int iInt;

                Console.Write("Enter a number for IF Else Example: ");            
                iInt = Int32.Parse(Console.ReadLine());
                if (iInt > 0)
                {
                    Console.WriteLine("{0} is greater than zero.", iInt);
                }

               if (iInt < 0)
                    Console.WriteLine("{0} is less than zero.", iInt);

                //simple example
                if (iInt != 0)
                {
                    Console.WriteLine("{0} is not equal to zero.", iInt);
                }
                else
                {
                    Console.WriteLine("{0} is equal to zero.", iInt);
                }
                //complex example
                if (iInt < 0 || iInt == 0)
                {
                    Console.WriteLine("{0} is less than or equal to zero.", iInt);
                }
                else if (iInt > 0 && iInt < 100)
                {
                    Console.WriteLine("{0} is between 1 and 100.", iInt);
                }
                else if (iInt > 101 && iInt < 200)
                {
                    Console.WriteLine("{0} is between 101 and 200.", iInt);
                }
                else if (iInt > 201 && iInt < 300)
                {
                    Console.WriteLine("{0} is between 201 and 300.", iInt);
                }
                else
                {
                    Console.WriteLine("{0} is greater than 300.", iInt);
                }
            }
            catch (Exception ex)
            {
                //handle exception here
            }
            Console.ReadLine();
        }
    }
}

How to use Array in C# | C# Array Examples

 

This is simple example to demonstrate the use of array. Please send us email or comment below if you feel any problem while using arrays.

How to use Array in C# | C# Array Examples

using System;
using System.Text;
using System.Data;
namespace Console_App
{
    public class clsArray
    {
        public static void Main()
        {
            try
            {
                int[] iInts = { 15, 20, 25 };
                bool[][] bBools = new bool[2][];
                bBools[0] = new bool[2];
                bBools[1] = new bool[1];
                double[,] dDoubles = new double[2, 2];
                string[] sStrings = new string[3];
                Console.WriteLine("Arrya Example");
                Console.WriteLine();

                Console.WriteLine("iInts[0]: {0}, iInts[1]: {1}, iInts[2]: {2}", iInts[0], iInts[1], iInts[2]);

                bBools[0][0] = false;
                bBools[0][1] = false;
                bBools[1][0] = true;
                Console.WriteLine("bBools[0][0]: {0}, bBools[1][0]: {1}", bBools[0][0], bBools[1][0]);

                dDoubles[0, 0] = 2.11;
                dDoubles[0, 1] = 1.830;
                dDoubles[1, 1] =11.111;
                dDoubles[1, 0] = 55.55667788;
                Console.WriteLine("dDoubles[0,0]: {0}, dDoubles[1,0]: {1}", dDoubles[0, 0], dDoubles[1, 0]);

                sStrings[0] = "Csharptalk.com";
                sStrings[1] = "Indihub.com";
                sStrings[2] = "bharatclick.com";
                Console.WriteLine("sStrings[0]: {0}, sStrings[1]: {1}, sStrings[2] {2}", sStrings[0], sStrings[1], sStrings[2]);
            }
            catch (Exception ex)
            {
                //handle exception here
            }
            Console.ReadLine();
        }
    }
}

Monday, September 20, 2010

Demo of Binary Operations in C#

Binary Operations are performed between two operands. here is few C# binary operation and their results.

Demo of Binary Operations in C#

Code:

using System;
using System.Text;
using System.Data;
namespace Console_App
{
    public class clsBinaryOperations
    {
        public static void Main()
        {
            try
            {
                int value1, value2, result;
                float floatResult;

                Console.WriteLine("Program for Binary Operations in C#");

                value1 = 5;
                value2 = 9;

                Console.WriteLine("Value of value1: {0}", value1);
                Console.WriteLine("Value of value2: {0}", value2);

                result = value1 + value2;
                Console.WriteLine("Result of value1+value2: {0}", result);

                result = value1 - value2;
                Console.WriteLine("Result of value1-value2: {0}", result);

                result = value1 * value2;
                Console.WriteLine("Result of value1*value2: {0}", result);

                result = value1 / value2;
                Console.WriteLine("Result of value1/value2: {0}", result);

                floatResult = (float)value1 / (float)value2;
                Console.WriteLine("Result of (float)value1 / (float)value2: {0}", floatResult);

                result = value1 % value2;
                Console.WriteLine("Result of  value1%value2: {0}", result);

                result += value1;
                Console.WriteLine("Result of  result+=value1: {0}", result);
            }
            catch (Exception ex)
            {
                //handle exception here
            }
            Console.ReadLine();
        }
    }
}

Friday, September 10, 2010

C# Program to Calculate Square Root of a Number

To calculate Square root of a number there is a inbuilt function inside the Math class. So you can directly use this function to find out the Square root of a number.

C# Program to Calculate Square Root of a Number

 

C# Program to Calculate Square Root of a Number

using System;
using System.Text;
using System.Collections;
using System.Data;
namespace Console_App
{
    public class clsFactorial
    {      
        public static void Main()
        {
            try
            {
                Console.WriteLine("Enter a number for Square Root:");
                 int Number =Convert.ToInt16( Console.ReadLine());
                 double SqrtNumber = Math.Sqrt(Number);

                 Console.WriteLine("Square root of Number {0} is: {1}", Number, SqrtNumber);                   
            }
            catch(Exception ex)
            {
                //handle exception here
            }
            Console.ReadLine();           
        }
    }
}

Thursday, July 15, 2010

How Dynamically Add Rows into ASP.NET Table using C#

This sample will help to add rows and cells into a asp.net table using C#.

You need to first create a row and then create a cell assign the properties of cell and then add the cell to row and then row to table.

 

How Dynamically Add Rows into ASP.NET Table using C#

 

How Dynamically Add Rows into ASP.NET Table using C# Example:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ">

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        TableRow tr = new TableRow();
        TableCell tc = new TableCell();
        tc.Text = "PetsMantra.com";
        tr.Cells.Add(tc);
        TableCell tc2 = new TableCell();
        tc2.Text = "Join2Green.com";
        tr.Cells.Add(tc2);
        tblSample.Rows.Add(tr);
    }
</script>

<html>
<head>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
        <asp:table ID="tblSample" runat="server"></asp:table>
        </div>
    </form>
</body>
</html>

Wednesday, July 14, 2010

How to restrict a dropdown selection in C#

You can restring a user to select particular value. Here is sample code to implement this using C#. on selection change event you can check for values and if it matches. Chnge the selected index to 0.

 

How to restrict a dropdown selection in C#

How to restrict a dropdown selection in C# Example:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" >
<script runat="server">

    protected void cmbMyList_SelectedIndexChanged(object sender, EventArgs e)
    {   
        Response.Write("You Have Selected: " + cmbMyList.SelectedValue + "<br>");
        if (cmbMyList.SelectedValue.ToString() == "Select 2")
        {
            Response.Write("You are not allowed to select 'Select 2'" );
            cmbMyList.SelectedIndex = 0;
        }      
    }
</script>

<html xmlns="">
<head>
    <title>
     </title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
           <asp:DropDownList ID="cmbMyList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="cmbMyList_SelectedIndexChanged">
           <asp:ListItem Text="Select 1" Value="Select 1"></asp:ListItem>
           <asp:ListItem Text="Select 2" Value="Select 2"></asp:ListItem>
           <asp:ListItem Text="Select 3" Value="Select 3"></asp:ListItem>
           <asp:ListItem Text="Select 4" Value="Select 4"></asp:ListItem>
           </asp:DropDownList>
        </div>
    </form>
</body>
</html>

Saturday, July 10, 2010

How to call both server side and client side methods on button click

This simple method helps you to call server side C# method and client side javascript methods togather with one click. just assign these two parameters with name of C# and javascript functions.

OnClick

OnClientClick

 

How to call both server side and client side methods on button click

 

How to call both server side and client side methods on button click Example:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" ">
<script runat="server">
    protected void btnClick_Click(object sender, EventArgs e)
{
Response.Write("Server side click.");
}
</script>
<script language="javascript">
function ClientClick()
{
alert('Client side click');
}
</script>

<html xmlns="">
<head>
    <title>call javascript and C# methods on single click.</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Button ID="btnClick"  runat="server" Text="Button" OnClientClick="ClientClick()" OnClick="btnClick_Click" />
        </div>
    </form>
</body>
</html>

Friday, July 9, 2010

How to use Trigger textchange event in textbox using C#

This C# program will help you deal with OnTextChanged event of textbox. This event occur when textbox text changes and user leaves the textbox.

you can perform any operation as per your requirement.

 

How to use Trigger textchange event in textbox using C#

 

How to use Trigger textchange event in textbox using C# Example:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" >

<script runat="server">
    protected void txtTextChanged_TextChanged(object sender, EventArgs e)
    {
      Response.Write("OnTextChanged event occured.");
    }

</script>

<html xmlns="">
<head>
    <title>How to use Trigger textchange event in textbox using C#.</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="txtTextChanged" runat="server" AutoPostBack="True" OnTextChanged="txtTextChanged_TextChanged"></asp:TextBox>
        </div>
    </form>
</body>
</html>

Thursday, July 8, 2010

How to Add MultiLine Textbox/TextArea in ASP.NET

To add multiline text box add a simple textbox in asp.net and set textmode property to MultiLine.

TextMode="MultiLine"

you can assign the maximum allowed characters also, to restrict error and unwanted spamming. if want that in particular mode textbox should not editable, you can add readonly property to false.

 

How to Add MultiLine Textbox/TextArea in ASP.NET

 

How to Add MultiLine Textbox/TextArea in ASP.NET Example:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" >

<html xmlns="">
<head>
    <title>How to use use textbox.</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" TextMode="MultiLine"  MaxLength="1000" Height="100" Width="300" runat="server"></asp:TextBox>
        </div>
    </form>
</body>
</html>

Wednesday, July 7, 2010

How to change HTML Meta tags using HtmlGenericControl in C#

This example wil help you to define your own meta tags using c#. just define a meta tag me ASPX page and assign values ( name and contents ) in C# file.

Like this line added in aspx page for description meta tag.

<meta id="MetaDescription" runat="server" />

And corresponding line added in C# which assign the values.

MetaDescription.Attributes["Name"] = "Description";

MetaDescription.Attributes["CONTENT"] = "Webpage meta description";

Now you can check the viewsource of the page to check the description meta tag.

<meta id="MetaDescription" Name="Description" CONTENT="Webpage meta description"></meta>

Webpage view source:

How to change HTML Meta tags using HtmlGenericControl in C#

How to change HTML Meta tags using HtmlGenericControl in C#

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" >

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        MetaDescription.Attributes["Name"] = "Description";
        MetaDescription.Attributes["CONTENT"] = "Webpage meta description";

        MetaKeyword.Attributes["Name"] = "Keyword";
        MetaKeyword.Attributes["CONTENT"] = "Webpage Meta Keywords";

    }
</script>

<html xmlns="">
<head>
    <title>Use of HtmlGenericControl class</title>
    <meta id="MetaDescription" runat="server" />
    <meta id="MetaKeyword" runat="server" />
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <h1>
                How to change HTML Meta tags using HtmlGenericControl.</h1>
        </div>
    </form>
</body>
</html>

Sunday, July 4, 2010

Page Inbuilt CSS Example in ASP.NET

This code will help you to add inbuilt style sheet in your webpage. Inside head tag define your css as given in exampe.

 

clip_image002

clip_image002[4]

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" >
<html xmlns=>
<head >
<title>ASP.NET - inbuilt CSS Example.</title>
<style type="text/css">
body {
font-family: Verdana;
}
a:link {
text-decoration: none;
color: Green;
}
a:hover {
text-decoration: underline;
color: red;
}
a:visited {
text-decoration: none;
color: blue;
}

</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<a href=>All india News</a>
</div>
</form>
</body>
</html>

Saturday, July 3, 2010

Validation Summary Example in ASP.NET

ASP.NET validaion summary is use to display summary for validation results. Suppose you have two controls first name and last name and there is a require field validation for each. Now if you add a validation summary, the failed validations will appear in validation summary instead of requirefieldvalidtions.

 

Validation Summary Example in ASP.NET

Validation Summary Example in ASP.NET

Validation Summary Example in ASP.NET

 

Validation Summary Example in ASP.NET Example:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" >
<html>
<body>
    <form id="Form1" runat="server">
        <h4>
            Validation Summary Example</h4>
        <br />
        Enter First Name:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="TextBox1"
            runat="server" ErrorMessage="Please Enter First Name" InitialValue="" Text="*" />
        <br />
        Enter Last Name:
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="TextBox2"
            runat="server" ErrorMessage="Please Enter Last Name" InitialValue="" Text="*" />
        <br />
        <asp:Button ID="Button1" Text="Submit" runat="server" />
        <br />
        <br />
        <asp:ValidationSummary ID="ValidationSummary1" HeaderText="You must enter a value in the following fields:"
            DisplayMode="BulletList" EnableClientScript="true" runat="server" />
    </form>
</body>
</html>

Friday, July 2, 2010

How to check/validate to select a radio button option | RequiredFieldValidator

You can also verify that a value should be selected in radio button list before processing. The sample code is given below, Please let me know in case of any erros while implementation.

How to check/validate to select a radio button option | RequiredFieldValidator

How to check/validate to select a radio button option | RequiredFieldValidator

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html>
<body>
    <form id="Form1" runat="server">
        <h4>
            Check for atleast one Radio button selection</h4>
        <br />
        Select a option:
        <asp:RadioButtonList ID="rdo_Websites" RepeatLayout="Flow" runat="server">
            <asp:ListItem>SoftwareTestingNet.com</asp:ListItem>
            <asp:ListItem>IndiHub.com</asp:ListItem>
            <asp:ListItem>BharatClick.com</asp:ListItem>
        </asp:RadioButtonList>
        <br />
        <asp:Button ID="Button1" Text="Submit" runat="server" />
        <br />
        <br />
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="rdo_Websites"
           Text="Please select a option" runat="server" />
    </form>
</body>
</html>

Thursday, July 1, 2010

How to Check for Selected Value in DropDownList using ASP.NET | RequiredFieldValidator

Now you can veryfy for selcted value in combobox using asp.net control RequiredFieldValidator. This control verifys for values at client side. So you just need to assign name of combobox in validation control and all id done.

 

How to Check for Selected Value in DropDownList using ASP.NET | RequiredFieldValidator

How to Check for Selected Value in DropDownList using ASP.NET | RequiredFieldValidator

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" >
<html>
<body>
    <form id="Form1" runat="server">
        <h4>
            Check for Selected Value</h4>
        <br />
        Select a Value:    
        <asp:DropDownList ID="DropDownList1" runat="server">
         <asp:ListItem></asp:ListItem>
        <asp:ListItem>Some Value</asp:ListItem>
        </asp:DropDownList>
        <br />
        <asp:Button ID="Button1" Text="Check" runat="server" />
        <br />
        <br />
        <asp:RequiredFieldValidator ID="MyRequiredFieldValidator" ControlToValidate="DropDownList1"
             ErrorMessage="Please select a value from doropdown to proceed." runat="server" />
    </form>
</body>
</html>

Thursday, June 24, 2010

Number Range Validator/Check in ASP.NET | RangeValidator

ASP.NET RangeValidator is very helpful to validate integer and double values range. You need not to write a javaScript code to check for number range niether write a C# code to validate at server side afterpost back.

So using this validation control you can avoid round trip to server.

 

Number Range Validator/Check in ASP.NET | RangeValidator

Number Range Validator/Check in ASP.NET | RangeValidator

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html>
<body>
    <form id="Form1" runat="server">
        <h4>
            Check for Number Range</h4>
        <br />
        Enter a Number:
        <asp:TextBox ID="txtNumber" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button1" Text="Validate" runat="server" />
        <br />
        <br />
        <asp:RangeValidator ID="IntRangeValidator1" ControlToValidate="txtNumber" Type="Integer"
            MaximumValue="1000" MinimumValue="100" SetFocusOnError="true" Text="The Number entered is not in given range, please enter a number between 100 to 1000."
            runat="server" />
    </form>
</body>
</html>

Tuesday, June 22, 2010

How to Validate/Check for Date in DateRange in ASP.NET

You can verify that given date in daterange or not just by using asp.net RangeValidator. You need not use javascript code niether validate date at server side.

Just use RangeValidator and give minimum and maximum date and all is done. Whereever user will enter a date out of this range it will prompt a error message and stop processing.

 

How to Validate/Check for Date in DateRange in ASP.NET

How to Validate/Check for Date in DateRange in ASP.NET

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" >
<html>
<body>
    <form id="Form1" runat="server">
        <h4>
            Check for Date Range</h4>
        <br />
        Enter Date:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button1" Text="Validate" runat="server" />
        <br />
        <br />
        <asp:RangeValidator ID="RangeValidator1" ControlToValidate="TextBox1" Type="Date"
            MaximumValue="10/10/2010" MinimumValue="01/01/2010" SetFocusOnError="true" Text="The Date entered is not in given range."
            runat="server" />
    </form>
</body>
</html>

Sunday, June 20, 2010

How to use CustomValidator to write oun validation script in ASP.NET

We can use CustomValidator to write our own complex validation at server side. Suppose we have to validate a phone number should be of 10 digit only so for that we can write a C# code to check lenth of phone number and if its not 10 digit just assign false to IsValid property.

args.IsValid = false;

 

How to use CustomValidator to write oun validation script in ASP.NET

How to use CustomValidator to write oun validation script in ASP.NET

 

How to use CustomValidator to write oun validation script in ASP.NET Example:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" >

<script runat="server">

    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        if (args.Value.ToString().Length != 10)
        {
            args.IsValid = false;
        }
    }
</script>

<html>
<body>
    <form id="Form1" runat="server">
        <h4>
            Check for Phone Number Length Validation</h4>
        <br />
        <br />
        Phone Number:
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button1" Text="Validate" runat="server" />
        <br />
        <br />
        <asp:CustomValidator ID="CustomValidator1" ControlToValidate="TextBox1" Text="Phone Number of 10 digits are allowed only."
            runat="server" OnServerValidate="CustomValidator1_ServerValidate" />
    </form>
</body>
</html>

Saturday, June 19, 2010

How to Compaire/Validate TextBox and DropDownList Values at client side in ASP.NET | CompareValidator

You can compaire a textbox and a Dropdownlist select value using asp.net comparevalidotor. Just give the name of both controls as given below.

 

How to Compaire/Validate TextBox and DropDownList Values at client side in ASP.NET | CompareValidator

How to Compaire/Validate TextBox and DropDownList Values at client side in ASP.NET | CompareValidator

 

How to Compaire/Validate TextBox and DropDownList Values at client side in ASP.NET | CompareValidator Example:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html>
<body>
    <form id="Form1" runat="server">
        <h4>
            Compare Two Password Values</h4>
        Textbox Value :
        <asp:TextBox ID="txtValues" runat="server" />
        <br />
        <br />
        Select Dropdown Value:
        <asp:DropDownList ID="DropDownList1" runat="server">
            <asp:ListItem>IndiHub.com</asp:ListItem>
            <asp:ListItem>SoftwareTestingNet.com</asp:ListItem>
        </asp:DropDownList>
        <br />
        <br />
        <asp:Button ID="Button1" Text="Validate" runat="server" />
        <br />
        <br />
        <asp:CompareValidator ID="compair_values" ControlToValidate="txtValues"
            ControlToCompare="DropDownList1" ForeColor="red" Type="string" Text="Please enter same value in textbox as selected in dropdown list."
            Operator="equal" runat="server" />
    </form>
</body>
</html>

Thursday, June 17, 2010

How to Compaire/Validate Two Password Values in ASP.NET | CompareValidator

Suppose you have two password fields and you want to copaire these fields that original password and reentered passwords are same or not?

Here is a simple solution to do client side validation. Use ASP.NET comparevalidator and assign these properties.

ControlToValidate="txtPassword1" ControlToCompare="txtPassword2"

Set type =”string”

And its all done. Now if you will enter wrong repassword then it will validate client side and prompt you with error.

How to Compaire/Validate Two Password Values in ASP.NET | CompareValidator

How to Compaire/Validate Two Password Values in ASP.NET | CompareValidator

 

How to Compaire/Validate Two Password Values in ASP.NET | CompareValidator Example:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html>
<body>
    <form id="Form1" runat="server">
        <h4>
            Compare Two Password Values</h4>
       Password Value 1:
        <asp:TextBox ID="txtPassword1" TextMode="Password" runat="server" />
        <br />
        <br />
        Password Value 2:
        <asp:TextBox ID="txtPassword2" TextMode="Password" runat="server" />
        <br />
        <br />
        <br />
        <asp:Button ID="Button1" Text="Validate" runat="server" />
        <br />
        <br />   
        <asp:CompareValidator ID="compair_Password_values"  ControlToValidate="txtPassword1" ControlToCompare="txtPassword2"
            ForeColor="red" Type="string"  Text="Please enter same Password values in both textboxes." Operator="equal"
            runat="server" />
    </form>
</body>
</html>

Wednesday, June 16, 2010

How to Compaire/Validate Two Double Values in ASP.NET | CompareValidator

Now in ASP.NET 2.0 and later version you can compaire double values of two textboxes on client side without using javascript code and going to server.

As you an check

12.0 and 12.00 are same double values and 12.0 and 12.001 are different values.

Please note that you can not compaire string values with double compairvalidator. It not not show any validation message.

 

How to Compaire/Validate Two Double Values in ASP.NET | CompareValidator

How to Compaire/Validate Two Double Values in ASP.NET | CompareValidator

 

How to Compaire/Validate Two Double Values in ASP.NET | CompareValidator Example:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html>
<body>
    <form id="Form1" runat="server">
        <h4>
            Compare Two Double Values</h4>
       Double Value 1:
        <asp:TextBox ID="txtDouble1" runat="server" />
        <br />
        <br />
        Double Value 2:
        <asp:TextBox ID="txtDouble2" runat="server" />
        <br />
        <br />
        <br />
        <asp:Button ID="Button1" Text="Validate" runat="server" />
        <br />
        <br />   
        <asp:CompareValidator ID="compair_double_values"  ControlToValidate="txtDouble1" ControlToCompare="txtDouble2"
            ForeColor="red" Type="Double"  Text="Please enter same double values in both textboxes."
            runat="server" />
    </form>
</body>
</html>

Tuesday, June 15, 2010

How to Compaire Two Integer Values in ASP.NET | CompareValidator

Compairing two integer values in asp.net 2.0 and above versions are very easy now. You can just use the CompareValidator control and given the first textbox name and second textbox name as given in below example.

012 and 12 integer values are same, so it is not giving any error.

While 12 and 120 are different integer values, so there is error message.

 

How to Compaire Two Integer Values in ASP.NET | CompareValidator

How to Compaire Two Integer Values in ASP.NET | CompareValidator1

 

How to Compaire Two Integer Values in ASP.NET | CompareValidator Example:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html>
<body>
    <form id="Form1" runat="server">
        <h4>
            Compare two Integer values</h4>
       Integer Value 1:
        <asp:TextBox ID="txtNumber1" runat="server" />
        <br />
        <br />
        Integer Value 2:
        <asp:TextBox ID="txtNumber2" runat="server" />
        <br />
        <br />
        <br />
        <asp:Button ID="Button1" Text="Validate" runat="server" />
        <br />
        <br />   
        <asp:CompareValidator ID="compair_values"  ControlToValidate="txtNumber1" ControlToCompare="txtNumber2"
            ForeColor="red" Type="integer"  Text="Please enter same integer values in both textboxes."
            runat="server" />
    </form>
</body>
</html>

Monday, June 14, 2010

CompareValidator in ASP.NET | How to Compaire Two String Values in ASP.NET

CompareValidator in ASP.NET | How to Compaire Two String Values in ASP.NET

ASP.NET 2.0 provide number of client side validation controls. One control is CompareValidator, which help to compare two values at client side without writing a javascript code. This example helps you to compare two string values without writing extra code.

Just assign ControlToValidate="txtName1" ControlToCompare="txtName2" the name of two textboxes need to compare and all is done.

 

CompareValidator in ASP.NET | How to Compaire Two String Values in ASP.NET Example:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html>
<body>
    <form id="Form1" runat="server">
        <h4>
            Compare two values</h4>
        Value 1:
        <asp:TextBox ID="txtName1" runat="server" />
        <br />
        <br />
        Value 2:
        <asp:TextBox ID="txtName2" runat="server" />
        <br />
        <br />
        <br />
        <asp:Button ID="Button1" Text="Validate" runat="server" />
        <br />
        <br />
        <br />
        <asp:CompareValidator ID="compair_values" Display="dynamic" ControlToValidate="txtName1" ControlToCompare="txtName2"
            ForeColor="red" Type="String" Text="Validation Failed!"
            runat="server" />
    </form>
</body>
</html>

Sunday, June 6, 2010

How to Generate Random Links in ASP-C#

 

How to Generate Random Links in ASP-C#

Sometimes we need to display random links while designing a web application. Here is a solution to implement this using ASP.NET-C# coding.

This is implemented using random number generator and then checking these number and display the url on the basis of generated numbers.

How to Generate Random Links in ASP-C# Example:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">

<html>
<body>

<%
Random r = new Random();

double dd = r.NextDouble() ;
if (dd > 0.7)
    Response.Write("<a href='#>C# Tutorials</a>");
else if (dd > .5)
    Response.Write("<a href='#'>Software Testing Tutorials</a>");
else
    Response.Write("<a href='#>SharePoint Tutorials</a>");

%>
<p>
Example of random link generator.
</p>

</body>
</html>

Friday, June 4, 2010

How to Redirect User to Different URL – Radio Buttons - using ASP-C#

 

How to Redirect User to Different URL – Radio Buttons - using ASP-C#

This example help you to code a asp.net C# coding to redirect the user to specific url on selecting a radio button.

 

How to Redirect User to Different URL – Radio Buttons - using ASP-C#

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">

<%
    if (Request.Form["select"] != null && Request.Form["select"] != "")
       Response.Redirect(Request.Form["select"]);

%>  

<html>
<body>
<form action="Default3.aspx" method="post">
<input type="radio" name="select"
value="#">
C# Tutorials<br>
<input type="radio" name="select"
value="#">
Software Testing Tutorials<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Thursday, June 3, 2010

How to set Priority of a Thread in C# | Example

How to set Priority of a Thread in C# | Example

While running the application in multithreaded application, a priority task need to finish first. C# allowes to set the priority of a thread by assigning the thread priority.

These are different types of thread priorities available in C#:

Zero

BelowNormal

Normal

AboveNormal

Highest

you can check the output of this program. the thread2 is started first but thread1 executed first and thread2 executed second. this is because thread1 have hieghest priority and thread2 have lowest priority.

sometimes the output of given program can differ from current one, because thread based program dipends on system configuration and running programs also.

 

How to set Priority of a Thread in C# | Example

using System;
using System.Text;
using System.Threading;

namespace Console_App
{

    public class Class1
    {
        public void fun1()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(" Thread-1 #" + i  );            
            }
        }

        public void fun2()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(" Thread-2 #" + i);
            }
        }
    }
    public class Class2
    {
        public static void Main()
        {
            Class1 a = new Class1();
            Thread thread1 = new Thread(new ThreadStart(a.fun1));
            Thread thread2 = new Thread(new ThreadStart(a.fun2));
            thread1.Priority = ThreadPriority.Highest;
            thread2.Priority = ThreadPriority.Lowest;
            thread2.Start();
            thread1.Start();
            Console.ReadLine();
        }
    }
}

Wednesday, June 2, 2010

How to run a thread in BackGround in C#

How to run a thread in BackGround in C#

Threads either run in background or foreground. There is a property by which one can know thred running status.

Thread.CurrentThread.IsBackground

One can force thread to run in background or forground by setting the property

thread1.IsBackground = true; //thread will run in background

thread1.IsBackground = false; //thread will run in foreground

like in current example the new thread is running in background and the parent thread is running in foreground.

 

How to run a thread in BackGround in C# Example:

using System;
using System.Text;
using System.Threading;

namespace Console_App
{

    public class Class1
    {
        public void fun1()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(" #" + i + "Running in Background: " + Thread.CurrentThread.IsBackground );            
            }
        }
    }
    public class Class2
    {
        public static void Main()
        {
            Class1 a = new Class1();
            Thread thread1 = new Thread(new ThreadStart(a.fun1));
            Console.WriteLine("Before Starting Thread - Running in Background: " + Thread.CurrentThread.IsBackground);
            thread1.Start();
            thread1.IsBackground = true;
            Console.WriteLine("After Staring Thread  - Running in Background: " + Thread.CurrentThread.IsBackground);           
            Console.ReadLine();
        }
    }
}

Sponsored Ad

Development Updates