Tuesday, 8 January 2013

Introduction to Generic List using Csharp and ASP.NET


Introduction to Generic List using Csharp and ASP.NET

Introduction:

C# List is a collection class which can hold any type of data. Unlike Array, List provides capability to add items without specifying the size.
This article will cover the following topics:
  • List- Add Item
  • List- Delete Item
  • List- Search
  • List- Sort
  • List- Display Data
  • List- Other Functionality

Initial UI and List with Social Network Data
Figure 1: Initial UI and List with Social Network Data

ASP.NET Script:

ASP.NET script is used to properly demonstrate the List functionality. The below script have the following items:
  • ASP.NET TextBox Controls
  • ASP.NET Label Controls and ListBox Control
  • ASP.NET Buttons Controls

Listing 1: ASP.NET Script for List Demonstration
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<head runat="server">
    <title> List Tutorial Part -1</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        List Item:
        <asp:TextBox ID="txtListItem" runat="server"></asp:TextBox> 
         
        <br />
        <br />
        Message:
        <asp:Label ID="lblListDisplay" runat="server" Text=""></asp:Label>
        <br />
        <br />
        List State:<br />
        <asp:ListBox runat="server" ID="lstSocialNetwork" Width="200px" Height="150px"
            > </asp:ListBox>
        <br />
        <br />
    <asp:Button ID="btnAdd" runat="server" Text="Add" OnClick="btnAdd_Click" />
    <asp:Button ID="btnDelete" runat="server" Text="Delete" OnClick="btnDelete_Click" />
     <asp:Button ID="btnSearch" runat="server" Text="Search"
     onclick="btnSearch_Click"  />
      <asp:Button ID="btnSort" runat="server" Text="Sort"
       onclick="btnSort_Click"  />       
         
    </div>
    </form>
</body>

C# Code:

Lets start with C# code for List. First thing you have to do is add the 
namespace for collection class.
1
2
using System;
using System.Collections.Generic;
Now create the object of List by
1
static List<string> SocialNetworkList;
Now initialize the object by
1
SocialNetworkList = new List<string>();
The above initializations says that the List is type of , it means you can store the value type of string.
The below is some initial data, which will load on page_load event. The data is the name of some social network sites.
Listing 2: List- Initial Data
1
2
3
4
5
6
//add the items in List
SocialNetworkList.Add("Facebook");
SocialNetworkList.Add("Linkedin");
SocialNetworkList.Add("Twitter");
SocialNetworkList.Add("Google+");
SocialNetworkList.Add("Orkut");

List- Add Item:

We have already seen that how to create and initialize the List object. Now will add some data into it. Use the Add() method to append the item in List.
Add Item - A item Added
Figure 2: Add Item - A item Added (“MySpace”)
Listing 3: List- Add Item Source Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (txtListItem.Text.Trim() != "")
        {         
             SocialNetworkList.Add(txtListItem.Text.Trim());

             lblListDisplay.Text = "List Item Added";           
        }
        else
        {
            lblListDisplay.Text = "List - Please Enter an Item to Add";
        }
        DisplayListBoxData();
    }

List- Delete Item:

There are two popular methods to remove the items from List - Remove() and RemoveAt(). The Remove method delete the data by value. However the RemoveAt delete the data by index.
Delete Item
Figure 3: Delete Item - (”Twitter”) is removed from List
Listing 4: List- Delete Item - Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
protected void btnDelete_Click(object sender, EventArgs e)
    {
        if (txtListItem.Text.Trim() != "")
        {
            if (SocialNetworkList.Contains(txtListItem.Text.Trim()))
            {
                SocialNetworkList.Remove(txtListItem.Text.Trim());
                //SocialNetworkList.RemoveAt(1);
                lblListDisplay.Text = "List Item Deleted";
            }
            else
            {
                lblListDisplay.Text = "Item Not Found.";
            }
        }
        else
        {
            lblListDisplay.Text = "List - Please Enter an Item to Delete";
        }
        DisplayListBoxData();
    }

List- Search:

List class have a Contains() method to search particular item by value. 
The below snippet shows the use of this method. Just pass the item into it and 
it will return true in case of item found and false if no result found.
Search
Figure 4: Search - The ‘Linkedin’ found in List
Listing 5: List- Search item - Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (txtListItem.Text.Trim() != "")
        {
          if (SocialNetworkList.Contains(txtListItem.Text.Trim()))
          {
            lblListDisplay.Text = "List Item Found";
          }
           else
            {
           lblListDisplay.Text = "List Item Not Found.";
            }
        }
      else
      {
        lblListDisplay.Text = "Please Enter an Item to Search";
        }
        DisplayListBoxData();
    }

List- Sort:

The List provide the Sort() method to sort All the data in it. This method sort the all item in ascending order. If you like to sort in descending order use the Reverse() method.
Sort
Figure 5: Sort- All the values are sorted now in ascending order
Listing 6: List- Sort data - Code
1
2
3
4
5
6
7
8
9
10
11
12
protected void btnSort_Click(object sender, EventArgs e)
    {
        SocialNetworkList.Sort();
        //Reverse sort
        //SocialNetworkList.Reverse();
        
        lblListDisplay.Text = "List Item Not Found.";
         
        DisplayListBoxData();
    }

List- Display Data:

The below snippet is using foreach loop to add each item in ListBox.
Listing 7: List- Loop through items and display data on ASP page
1
2
3
4
5
6
7
8
9
private void DisplayListBoxData()
    {
        lstSocialNetwork.Items.Clear();
        foreach (string str in SocialNetworkList)
        {
            lstSocialNetwork.Items.Add(str);
        }
        
    }

List- Other Functionality:

Apart from above common operations, C# List provide some more common functions.
  • Count: Returns the item count
  • Clear(): Clear the items of List
  • Capacity : Returns the capacity of List.

Listing 8: List- Other operation
1
2
3
4
5
6
7
8
9
10
private void OtherFunctionality()
    {       
        //Clear all the items of List
        SocialNetworkList.Clear();
lblListDisplay.Text = " Count of All the Items of List: " + SocialNetworkList.Count;
lblListDisplay.Text = " Capacity of All the Items of List: " + SocialNetworkList.Capacity;
    }

Conclusion:

The above features are some most common one with c# list in next tutorial I will cover the other features of List. Please comment in case of any issues or suggestions.

No comments:

Post a Comment