Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Introduction to Generic List using Csharp and ASP.NET

This article will cover the following topics: how to add item, delete item, search, sort, display data and other functionalities from list.

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

<head runat="server">
    <title>MrBool.com - 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.

using System;
using System.Collections.Generic;

Now create the object of List by

static List<string> SocialNetworkList; 

Now initialize the object by

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

//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

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

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

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

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

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

 
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.



I am having total 7+ years of experience in developing applications using C#, VB.NET, ASP.NET, Silverlight, WCF, SQL Server and Oracle. I am holding a M.Tech degree in Intelligent systems. For more information, visit my Linkedin p...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login