Friday, 30 August 2013

HashTable example in c#.

HashTable:-
A hash table is used when you need to access an element using key. Each item in a hash table has a key/value pair. The key is used to access the item in collection.

Properties Of  HashTable  Class:-
Count :- Gets the number of elements actually contained thr hashtable.
IsFixedSize :- Gets a value indicating whether the hashtable has fixed size.
IsReadOnly :-  Gets a value indicating whether the hashtable has ReadOnly.
Item :- Gets or sets the elements at specified index.
Key :- Gets an ICollection containing the keys in the hashtable.
Value :- Gets an ICollection containing the values in the hashtable.

Methods Of HashTable Class :-
There are various methods in hashtable class for ex. Add(), Clear(),Remove() etc. I have explained all methods in below example of hashtable.

Example:-
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Data;

namespace CollectionExample
{
    class Program
    {
//HashList Example-------------------------------------------------------------------------
            Console.WriteLine("-------------Hash table Example---------------");
            Hashtable ht = new Hashtable();

            ht.Add("1", "Sushil");
            ht.Add("2", "Kumar");
            ht.Add("3", "Sanjay");
            ht.Add("4", "Muthu");
            ht.Add("5", "Ashu");

            ht.Remove("1");

            if (ht.ContainsValue("Mantra"))
            {
                Console.WriteLine("This name already exist in HashTable.");
            }
            else
            {
                ht.Add("6", "Mantra");
            }

            ICollection key = ht.Keys;// to get collection of key

            foreach (string s in key)
            {
                Console.WriteLine(s + " " + ht[s]);
            }

            Console.ReadKey();
      }
   }
}

Output:-
-------------Hash table Example---------------
3 Sanjay
6 Mantra
4 Muthu
5 Ashu

2 Kumar

Thursday, 29 August 2013

ArrayList example in c#.

ArrayList :-

It is an alternative to array. However unlike array you can add and remove items from a list of specified postion using an index and the array resize itself automatically. It allows dynamic memory allocation, Add, search and sort items in the list.

Properties of ArrayList :-
Capacity :- Gets or sets the number of elements that ArrayList can contain.
Count :- Gets the number of elements actually contained thr ArrayList.
IsFixedSize :- Gets a value indicating whether the ArrayList has fixed size.
IsReadOnly :-  Gets a value indicating whether the ArrayList has ReadOnly.
Item :- Gets or sets the elements at specified index.

Methods of ArrayList :-
 There are 15 methods in Arraylist i.e Add(),Clear(),AddRange() which are explained in example. Below example has given in which all methods have used.

Example:-

using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Data;

namespace CollectionExample
{
    class Program
    {
static void Main(string[] args)
        {
            // ArrayList Example ---------------------------------------------------------------
            ArrayList arrayList = new ArrayList();
            Console.WriteLine("Adding some Number.");

            arrayList.Add(12);
            arrayList.Add(34);
            arrayList.Add(54);
            arrayList.Add(23);
            arrayList.Add(65);
            arrayList.Add(33);
            arrayList.Add(89);
            arrayList.Add(39);

            Console.WriteLine("Capacity :{0}", arrayList.Capacity);
            Console.WriteLine("Count :{0}", arrayList.Count);

            Console.Write("Content: ");
            foreach (int i in arrayList)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();
            Console.Write("Sorted Content: ");
            arrayList.Remove(12);//remove item 12
            arrayList.RemoveAt(1);//remove item from specified position using index
            arrayList.RemoveRange(2, 4);//remove no of item from specified position
            arrayList.Sort();// sorting arrayList
            foreach (int i in arrayList)
            {
                Console.Write(i + " ");
            }
            Console.WriteLine();
            Console.ReadKey();
        }
    }
}

Output:-
Adding some Number.
Capacity :8
Count :7
Content:12 34 54 23 65 33 89 39

Sorted Content: 23 34 

Collection in c#.

Collection provide a more flexible way to work with group of objects. Unlike arrays , the group of objects you work with can grow and shrink  dynamically as the needs of the application change.

Collection is a class , so you must declare a new collection before you can add elements to that collection.

Collection classes are specialized classes for data storage and retrieval. Collection classes provide for stack ,queues,list and hash tables.

Collection classes are various purposes , such as allocating memory dynamically to element and accessing a list of items on the basis of an index etc.

For using the Collection , You have to add System.Collections namespace in your coding.

Types of collection classes and there Usage:-




Class
Description and Usage
ArrayList
It is an alternative to array. However unlike array you can add and remove items from a list of specified postion using an index and the array resize itself automatically. It allows dynamic memory allocation,
Add, search and sort items in the list.
HashTable
A hash table is used when you need to access an element using key. Each item in a hash table has a key/value pair. The key is used to access the item in collection.
SortedList
It is the combination of Arraylist and hashTable . It contains a list of items that can be accessed by using a key or an index. If you access items using an index , it is an arraylist ,and if you are accessing an item using a key , it is a hashtable. The collection of items is always sorted by the key value.
Stack
It represents a last-in , first out collection of objects.
It is used when you want a last in ,first out access of items. When you add an item in the list , it is called pushing the item and when you remove it , it is called poping the item.
Queue
It represents a first in, first out collection of object.
It is used when you want a first in, first out access of items. When you add an item in the list , it is called enqueue and when you remove an item , it is called dequeue.
BitArray
It is represent an array of the binary representation using the values 1 and 10.
It is used when you want to store the bits but do not know the number of bits in advance. You can access items from the BitArray collection by using an integer index which start from 0(Zero).

What is MVC in Asp.net.

The Model-View-Controller architectural pattern separates an appliaction into three component : The Model,The View and The Controller.The Asp.Net MVC framework is an alternative to the Asp.Net web form pattern for creating MVC based web application.
It is a light weight framework, highly testable presentation framework that is integrated with existing Asp.Net feature, such as master page and form authentiactions.The MVC framework is defined in System.Web.Mvc namespace.

Understanding  Model:-
An MVC model contains all of your application logic that are not contained in Views or Controller. The Model contains all of business logic, database access logic and validation logic.
For example, If you are using Microsoft Entity Framework to access your database, then you would create your entity framework class (.edmx file) in the model folder.

Understanding  View:-
A view contain html markup and content that is sent to the browser. A view is equivalent to the page when working with an asp.net MVC.

Understanding  Controller:-
A controller is responsible for controlling the way user interacts with MVC appliaction. A controller contains the flow control logic for MVC appliaction. A controller determines what reponse to send back to the user when a user make a browser request.
Controller is just  a class(.cs file).



                   

Wednesday, 28 August 2013

What is Collection Initializer in c#.

Collection Initializer is used to create an instance of collection class and assign a value to any accessible fields or properties of it at the same time. It is not necessary to explicitly create a constructor.

Example:-

class Cat
{
    // Auto-implemented properties.
    public int Age { get; set; }
    public string Name { get; set; }
}

List<Cat> cats = new List<Cat>()
{
    new Cat(){ Name = "Sylvester", Age=8 },
    new Cat(){ Name = "Whiskers", Age=2 },
    new Cat(){ Name = "Sasha", Age=14 }
};

OR:-


List<int> MyInts = new List<int>() { 1, 2, 3, 5, 6, 7 };

Wednesday, 21 August 2013

Lambda expression in Linq.

Lambda expression is one of the features introduced in c# 3.0. Lambda expression helps you to ease the burden of verbose of anonymous functions or methods.

Lambda expression is anonymous function or method that you can use to create delegates or expression tree type. Lambda expressions use lambda operator i.e =>.

Lambda expression:-

      x => x*x;

  •     The left hand side of operator specified input parameter.
  •     The right hand side of operator is expression or statement.


In the above lambda expression , x on the left hand side is input parameter and the right hand side is expression that return the result of value (x*x) of input x.


Let see the below example to better understand of lambda expression.

In this example lambda expression, with collection to find out employee details using empId.

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

namespace LambdaInLinq
{
    class Program
    {
        static void Main(string[] args)
        {
            EmpDetails empDetail = new EmpDetails();
            clsEmployee empDetails = empDetail.FindEmpById("EMP1");
            if (empDetails == null)
            {
                Console.WriteLine("Emp does not exist.");
            }
            else
            {
                Console.WriteLine("Name:"+empDetails.EmpName);
                Console.WriteLine("ID:" + empDetails.EmpId);
                Console.WriteLine("DOB:" + empDetails.DOB);
                Console.WriteLine("DOJ:" + empDetails.DOJ);
            }
            Console.ReadLine();
        }
        public class clsEmployee
        {
            public string EmpId { get; set; }
            public string EmpName { get; set; }
            public DateTime DOB { get; set; }
            public DateTime DOJ { get; set; }
        }
        public class EmpDetails
        {
            //creating object
            List<clsEmployee> listEmp = new List<clsEmployee>();
            //initializing the details using constructor
            public EmpDetails()
            {
                AddEmpDetails();
            }
            //adding the employee details in listEmp
            public void AddEmpDetails()
            {
                listEmp.Add(new clsEmployee { EmpId = "EMP1", EmpName = "Sushil", DOB = DateTime.Now.Date.AddYears(-20) });
                listEmp.Add(new clsEmployee { EmpId = "EMP2", EmpName = "Ashu", DOB = DateTime.Now.Date.AddYears(-21) });
                listEmp.Add(new clsEmployee { EmpId = "EMP3", EmpName = "Sanjay", DOB = DateTime.Now.Date.AddYears(-35) });
            }
            // method to find employee Details in listemp using Lambda expression
            public clsEmployee FindEmpById(string EmpId)
            {
                return listEmp.Find(m => m.EmpId == EmpId);
            }
        }
       
    }
}

Monday, 5 August 2013

How to create Dynamic Textbox on button Click Event In Asp.Net.

In this article ,I have explained how to create dynamic  textbox on button click event in asp.net using c#. Dynamic control is easy to handle in the program. In this article I have created no of textbox  as per requirement of user or data.

Design.aspx:-

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:Button ID="Button1"
            runat="server" Text="Button" onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>

Code Behind Page:-

protected void Button1_Click(object sender, EventArgs e)
    {
        int no = Convert.ToInt32(TextBox1.Text);
       
       for (int i = 0; i < no; i++)
        {
            string name = "TextBox"+i.ToString();
            TextBox text = new TextBox();
            text.ID = name;
            text.Width=100;
            text.Height = 25;
            form1.Controls.Add(text);
           
        }
    }


When you will on click button control it will create no buttons as values inserted in textbox.