Sponsored Ad

Saturday, May 29, 2010

Tostring() Operator Overloading in C#

Tostring() Operator Overloading in C#

ToString() Operator Overloading is laso possible in C#. You just have to wite a override ToString() method to add extra/Different functionality. The ToString() override method exapmle is given below, where it write an addition line on console as well as it passes a constant string back to writeline method.

Please note that ToString method get called twice in this example. Because the first writeline statement automatically call this override method.

Console.WriteLine(a1);

In case you feel any difficulty while implementing this. Please comment.

Tostring() Operator Overloading in C# Example:

using System;
using System.Collections.Generic;
using System.Text;

namespace Console_App
{
    public class Class1
    {
        public static void Main()
        {
            Class2 a1 = new Class2(10);
            Console.WriteLine(a1);
            Console.WriteLine();
            Console.WriteLine(a1.ToString());
            Console.ReadLine();
        }
    }
    public class Class2
    {
        public int i;
        public Class2(int j)
        {
            i = j;
        }
        public override string ToString()
        {
            Console.WriteLine("ToString() Method Get Called. ");
            return "ToString() Operator OverLoading. ";
        }
    }
}

Friday, May 28, 2010

How to Get Form Values using ASP-C# | Post Mehtod Example

How to Get Form Values using ASP-C# | Post Mehtod Example

 

This simple asp-C# code will help you to get the form values with post mehtod. Assign the current page name into action="Default3.aspx" property of form and fill the text box with some values and click the submit button.

You can recieve the textbox values using

strValue=Request.Form["txtValue"];

where txtValue is the name of TextBox.

 

How to Get Form Values using ASP-C# | Post Mehtod Example:

 

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

<html>
<body>
<form action="Default3.aspx" method="post">
Your name: <input type="text" name="txtValue" size="20">
<input type="submit" value="Submit">
</form>
<%
string strValue;
strValue=Request.Form["txtValue"];
if( strValue != "")
    {
      Response.Write("Value of TextBox is: <b> " + strValue + " </b><br />");
      Response.Write(" Do you Like it ? ");
    }

%>
</body>
</html>

Thursday, May 27, 2010

Working with Collections | Collection Loop Through Example using foreach

Working with Collections

 

Collections are new to some programmers. So we desided to write a post on this. Collections are ingherited from IEnumerator interface.

In this example Class3 contains the three methods of Class3 interface and in this class these 3 methods implemented.

MoveNext()

Reset()

And a property Current

So using forearch now you can loop through the all collection objects. Also you need to explicitly check for iteration count in MoveNext()

Method. Because it does not take care internally.

 

Working with Collections | Collection Loop Through Example using foreach

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace Console_App
{
    public class Class1
    {
        public static void Main()
        {
            Class2 obj = new Class2();
            foreach (string str in obj)
            {
                Console.WriteLine(str);
                Console.WriteLine();
            }

            Console.ReadLine();
        }
    }
    class Class2
    {
        public IEnumerator GetEnumerator()
        {
            return new Class3();
        }
    }
    class Class3 : IEnumerator
    {
        public string[] a1 = new string[3] { "String 1", "String 2", "String 3" };
        public int i = -1;
        public bool MoveNext()
        {
            i++;
            Console.WriteLine("MoveToNext Value: " + i);
            if (i == 3)
                return false;
            else
                return true;
        }
        public void Reset()
        {
            Console.WriteLine("Reset");
        }
        public object Current
        {
            get
            {
                Console.WriteLine("Current Value : " + a1[i]);
                return a1[i];
            }
        }
    }
}

Tuesday, May 25, 2010

Oprator Overloading with Less than (<) and Greater than Operators in C#

Oprator Overloading with Less than (<) and Greater than Operators in C#

This program helps you to implement operator overloading with less than (<) and greater than (>) operators. We have created two objects and assign values 9 and 7 to those operators. After comparing these objects displaying the true and false value.

In case of any problem while implementation, you can contact us by commenting to this post.

Oprator Overloading with Less than (<) and Greater than Operators in C# Example:

using System;
using System.Collections.Generic;
using System.Text;

namespace Console_App
{
    public class Class1
    {
        public static void Main()
        {
            Class2 a1 = new Class2(9);
            Class2 a2 = new Class2(7);

            Console.WriteLine("Example 1:");
            Console.WriteLine();
            if (a1 > a2)
                Console.WriteLine("Result: true");
            else
                Console.WriteLine("Result: false");
            Console.WriteLine();
            Console.WriteLine();
            Console.WriteLine("Example 2:");
            Console.WriteLine();
            if ( a2 > a1)
                Console.WriteLine("Result: true");
            else
                Console.WriteLine("Result: false");

            Console.ReadLine();
        }
    }
    public class Class2
    {
        public int i;
        public Class2(int j)
        {
            i = j;
        }
        public static bool operator >(Class2 x1, Class2 x2)
        {
            System.Console.WriteLine(" " + x1.i + " > " + x2.i);
            return x1.i > x2.i;
        }
        public static bool operator <(Class2 x1, Class2 x2)
        {
            System.Console.WriteLine(" " + x1.i + " < " + x2.i);
            return x1.i < x2.i;
        }
    }
}

Monday, May 24, 2010

C# Function Overloading

In C# we can have function with the same name, but we have to take different data type. We called the function by the same name as by passing different parameters and a different function gets called. That’s Process called function overloading .In the following code we have three function and all of having same name aaa.

 

C# Function Overloading Examples

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{

    class xxx
    {
        public static void Main()
        {
            zzz a = new zzz();
            a.function(10);
            a.function("Hello");
            a.function("Number", 100);
        }
    }
    class zzz
    {

        public void function(int i)
        {
            System.Console.WriteLine("Name" + i);
        }

        public void function(string i)
        {
            System.Console.WriteLine("Name" + i);
        }

        public void function(string i, int j)
        {
            System.Console.WriteLine("Name" + i + j);
            System.Console.ReadLine();
        }
    }
}

Output

 

C# Function Overloading

Friday, May 21, 2010

How to Implement (H1) Heading 1 to (H6) Heading 6 in ASP.NET - C#

How to Implement (H1) Heading 1 to (H6) Heading 6 in ASP.NET - C#

This demo program will help you to code all heading available in HTML using C# code. This C# code is implemented in aspx page. The whole program is given below. Please let us know if you have any questions.

Source code of How to Implement (H1) Heading 1 to (H6) Heading 6 in ASP.NET - C#

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

<%

for (int i = 1; i <= 6; i++)
{
    Response.Write("<h" + i + ">Heading " + i + "</h" + i + ">");
}

%>

</body>
</html>

Thursday, May 20, 2010

How to Declare variable in ASP.NET Page using C#

How to Declare variable in ASP.NET Page using C#

Server side coding (C#, VB or any other language can be used with ASP.NET page. Here is sample code to implement the same. ASP.NET page allowes developer to write C# sysntax inside the <% %> block. Its mease it can contain C# block of code same as written in .cs file.

This simple program declare a string and print it using c# sysntax. The whole code for aspx page is given below. Please note that This page does not contain the .cs file.

you need to add AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" in Page directive to work with .cs file.

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

Source code of How to Declare variable in ASP.NET Page using C#

<html>
<body>

<%
string  strStatement;
strStatement = "This is an example of C# coding within ASP.NET Page.";
Response.Write("My Statement is: " + strStatement);
%>

</body>
</html>

How to add and Remove items from Queue using C# | Queue Example

 

C# 2.0 collection classes contains the Queue collection to represent the queue, by using this class you can easily insert and remove the queue functionality. Please note that Queue works as FIFO(First in First out) basis.

 

Output of Queue program:

How to add and Remove items from Queue using C# | Queue Example

 

Source Code of Queue Program:

using System;
using System.Text;
using System.Collections;
namespace Console_App
{
    public class Class2
    {
        public static void Main()
        {
            Queue objQueue = new Queue();

            objQueue.Enqueue("String 1");
            objQueue.Enqueue(100);
            objQueue.Enqueue(99.99);

            Console.WriteLine(" Queue contents:");
            foreach (object temp in objQueue)
            {
                Console.WriteLine(temp);
            }

            Console.WriteLine(" Removing from Queue:");
            while (objQueue.Count != 0)
            {
                object temp = objQueue.Dequeue();
                Console.WriteLine(temp + " is removed from Queue");
            }

            Console.ReadLine();
        }
    }

}

Wednesday, May 19, 2010

How to Add BackGround Color Using CSS

Add BackGround Color Using CSS

While designing a webpage, the most important thing is to give colors to give colors to user controls. In HTML and ASP.NET we can fill colors by using CSS properties. "background-color:" is property to assign background color of a control. Like in given example we have three controls along with body of the page. every control including body have the background color using different methods. h2 have transparent color, by default controls have transparent background colors.

Source code How to Add BackGround Color Using CSS

<html>

<head>

<style type="text/css">

body {background-color: silver}

h1 {background-color: #00fff0}

h2 {background-color: transparent}

p {background-color: rgb(250,0,200)}

</style>

</head>

<body>

<h1>Header 1 (H1) Background color</h1>

<h2>Header 2 (H2) Background color</h2>

<p>Paragraph Background color</p>

</body>

</html>

Saturday, May 15, 2010

How to Display Date in Reverse Format in C#

Sometimes we need to play with date and we need to display date in reverse format. So I am here with a C# code research.

This example is for today’s date while you can change this code to display any date in reverse format.

Source code  Display Date in Reverse Format in C#:

private string ReversedDateString( )
        {
            string reversedDate;

            // year component
            reversedDate = DateTime.Now.Year.ToString().Substring( 2, 2 );

            // month component
            reversedDate += DateTime.Now.Month.ToString( "00" );

            // day component
            reversedDate += DateTime.Now.Day.ToString( "00" );

            return reversedDate;
        }

Thursday, May 13, 2010

Switch Statement Example in C#

 

This is simple C# switch example. Which takes integer parameter and based on input it prints the string values. If no match found it executes Default case.

You can also use string values in switch statements.

 

Output:

Switch Statement Example in C#

 

Source code of Switch Statement:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Program obj = new Program();
            obj.SwitchExample(2);
            obj.SwitchExample(12);

            Console.ReadLine();          

        }

        private void SwitchExample(int temp)
        {
            switch (temp)
            {
                case 2:
                    Console.WriteLine("Number Two");
                    break;
                case 3:
                    Console.WriteLine("Number three");
                    break;
                default:
                    Console.WriteLine("Other Number");
                    break;
            }
        }
    }
}

Wednesday, May 12, 2010

Enum Example in C# | How Enum Works

 

Enums are used to create a new data type. It is basically use to give a user friendly name to an integer value.

Like in given example

enum eTest

{

a1 = 4, a2, a3 = 9, a4

}

We have created a enum with name eTest and it have 4 variable which are associated with different integer values.

A1=4

A2=5

A3=9

A4=10

Enum by default start with 0 and keep incrementing 1 value for next variables.

 

Output:

Enum exampe output

 

Source Code:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        enum eTest
        {
            a1 = 4, a2, a3 = 9, a4
        }

        static void Main(string[] args)
        {
            Program obj = new Program();
            obj.EnumExample();
            Console.ReadLine();
        }

        private void EnumExample()
        {
            Console.WriteLine((int)eTest.a1 + " " + (int)eTest.a2 + " " + (int)eTest.a3 + " " + (int)eTest.a4);
        }
    }
}

Tuesday, May 11, 2010

How to Declare variable in ASP.NET Page using C#

How to Declare variable in ASP.NET Page using C#

Server side coding (C#, VB or any other language can be used with ASP.NET page. Here is sample code to implement the same. ASP.NET page allows developer to write C# syntax inside the <% %> block. Its means it can contain C# block of code same as written in .cs file.

This simple program declare a string and print it using c# syntax. The whole code for aspx page is given below. Please note that This page does not contain the .cs file.

you need to add AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" in Page directive to work with .cs file.

 

Source Code:

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>

<body>

<%

string strStatement;

strStatement = "This is an example of C# coding within ASP.NET Page.";

Response.Write("My Statement is: " + strStatement);

%>

</body>

</html>

Set Image Properties in a webpage

 

Set Image Properties in a webpage

 

Sometimes while designing webpage, placing a image and setting their properties are touph task. This example helps you to arrange a image on webpage using background-image property. with some other image arrangement properties. Let me know if you face any problem while arranging a image.

Source Code:

<html>

<head>

<style type="text/css">

body{ background-image: url('Sunset.jpg'); background-repeat: no-repeat; background-position: center; }

</style>

</head>

<body>

</body>

</html>

Monday, May 10, 2010

Check Characters of String for All Digits in C#

 

This program will help you to check character by character string that it contains the digits or not.

There is separate method to check this functionality , you can copy and paste to your program to use it.

Digits along with Char - C#

Digits along with No Char - C#

Source code:

using System;
using System.Collections.Generic;
using System.Text;

namespace MyFirstConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("This is my First Console Application");
            // user input
            Console.WriteLine("Please enter some string:");
            string strInput = Console.ReadLine();
            Console.WriteLine("you have entered a string: " + strInput);
            Console.WriteLine();
            bool blnResults = CheckForDigits(strInput);
            strInput = blnResults?"Yes":"No";
            Console.WriteLine("String contains the all digits? " + strInput);

            Console.WriteLine("Press any key to exit.");
            Console.ReadLine();
        }

        public static bool CheckForDigits(string strTemp)
        {
            //remove white spaces
            strTemp = strTemp.Trim();

            if (strTemp.Length == 0)
            {
                return false;
            }
            // loop through the string
            for (int i = 0; i < strTemp.Length; i++)
            {
                if (Char.IsDigit(strTemp[i]) == false)
                {
                    return false;
                }
            }
            return true;
        }
    }
}

Wednesday, May 5, 2010

How to pass and return arrays in methods using C#

 

This sample program will help you to pass arrays and returns arrays from a function in C#. use the below program to develop complex functions to return and accept values.

Output:

How to pass and return arrays in methods using C#

source Code:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            int[] intArray = {  1 ,  2, 3 , 4, 5 };
            Program obj = new Program();
            int[] ResultArray = obj.PassArray(intArray);

            foreach (int ArrayItem in ResultArray)
            {
                Console.Write(ArrayItem + " ");
            }
            Console.ReadLine();

        }

        private int[] PassArray(int[] tempArray)
        {
            return tempArray;
        }
    }
}

Tuesday, May 4, 2010

How to Get Selected Date of Calendar using C#

 

This is small demonstration of a C# program to get selected date of a calendar using C#.

Calendar expose a method to get the selected date. there is other more methods, you can go though them one by one.

cldTest.SelectedDate.ToShortDateString()

 

How to Get Selected Date of Calendar using C#

 

Program Code:

 

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void cldTest_SelectionChanged(object sender, EventArgs e)
    {
        Response.Write("Your Date Selection is: " + cldTest.SelectedDate.ToShortDateString() + "<br>");       

    }
</script>

<html>
<head>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Calendar ID="cldTest" runat="server" OnSelectionChanged="cldTest_SelectionChanged"></asp:Calendar>
        </div>
    </form>
</body>
</html>

Monday, May 3, 2010

Number and Currency formatting in C#

 

The formats are given below along with example, please let me know if you face any problem.

 

Output:

Number and Currency formatting in C#

 

Source code:

using System;
using System.Collections.Generic;
using System.Text;

namespace MyFirstConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int intResults = 1234567890;
            double dblResults = 12345678.90;

            Console.WriteLine("Currency format {0}: {1:C}", "{C}", intResults);

            Console.WriteLine("Decimal format {0}: {1:D}", "{D}", intResults);

            Console.WriteLine("Decimal format {0}: {1:D12}", "{D12}", intResults);

            Console.WriteLine("Exponential format {0}: {1:E}", "{E}", intResults);

            Console.WriteLine("fixed format {0}: {1:F}", "{F}", intResults);

            Console.WriteLine("fixed format {0}: {1:F5}", "{F5}", intResults);

            Console.WriteLine("number format {0}: {1:N}", "{N}", dblResults);

            Console.WriteLine("number format {0}: {1:N1}", "{N1}", dblResults);

            Console.WriteLine("hexadecimal format {0}: {1:X}", "{X}", intResults);

            Console.WriteLine(" format {0}: {1:0.000}", "{0.000}", intResults);

            Console.WriteLine(" format {0}: {1:0.##}", "{0.##}", intResults);

            Console.WriteLine("percent format {0}: {1:0%}", "{0%}", intResults);

            Console.ReadLine();
        }

    }
}

How to Get Selected Values of CheckBoxList in C#

 

This sample code will help you to find the CheckBoxList selected values. This code loop through all the checkbox values using foreach and assign comma separated selected values in to label.

 

How to Get Selected Values of CheckBoxList in C#

 

 

Source code:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void btnGetSelected_Click(object sender, EventArgs e)
    {
        lblSelected.Text = "Your selected check box values are: <br>";
        foreach (ListItem lst in chkList.Items)
        {
            if (lst.Selected == true)
            {
                lblSelected.Text += lst.Text + ", ";
            }
        }
    }
</script>

<html>
<head>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:CheckBoxList ID="chkList" runat="server">
                <asp:ListItem>IndiHub.com</asp:ListItem>
                <asp:ListItem>BharatClick.com</asp:ListItem>
                <asp:ListItem>SharePointBank.com</asp:ListItem>
                <asp:ListItem>SoftwareTestingNet.com</asp:ListItem>
            </asp:CheckBoxList>
            <br />
            <asp:Button ID="btnGetSelected" runat="server" Text="Get Selected Values" OnClick="btnGetSelected_Click" />
            <br />
            <asp:Label ID="lblSelected" runat="server" Text=""></asp:Label>
        </div>
    </form>
</body>
</html>

How to Find Checkbox Status in C#

 

This sample code will help you to find checkbox status on check change.

 

How to Find Checkbox Status in C#

 

How to Find Checkbox Status in C#

 

Source code:

 

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    protected void chkTest_CheckedChanged(object sender, EventArgs e)
    {
        if (chkTest.Checked)
        {
            Response.Write("you have checked the checkbox");
        }
        else
        {
            Response.Write("you have unchecked the checkbox");
        }
    }
</script>

<html>
<head>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:CheckBox ID="chkTest" runat="server" AutoPostBack="true" OnCheckedChanged="chkTest_CheckedChanged"    />
        </div>
    </form>
</body>
</html>

Saturday, May 1, 2010

How to Create First Windows Application and Run in VS 2005 – C#

 

Creating a first project is always a tough talk. Let me demonstrate you to create a windows application in VS 2005 using C#.

 

Step 1: Open VS 2005 (IDE)

VS 2005

 

Step 2: Select Visual C# and windows application and give project name .

Select Visual C# and Windows Application and Given name to project

Step 3: form.cs is ready this is the main screen where we need to add controls. Click on Toolbox to get list of .NET controls.

Click on toolbox button

 

Step 4: Inside toolbox click on common controls.

vs with toolbox

 

Step 5: From The toolbox drag and drop the controls ( TextBox, Label, and Button)

Add Controls in VS 2005

 

step 6: now UI is ready and you can run the project and test it. just press F5 to run the project or click on run button.

change The Name of Label in VS 2005

 

Step 7: This is output of our program. Now you have to write login to perform certain operations.

Output

Sponsored Ad

Development Updates