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

Working with ArrayList using C# and ASP.NET - Basic and Advance

This article will cover advanced as well as the basic functionality of ArrayList.

Introduction:

Array is collection of similar data type, to overcome the limitation of Array Microsoft introduce the ArrayList which can store any multiple data types in one array. This article will cover advance as well as the basic functionality of ArrayList.

  1. Add Item in ArrayList
  2. Delete Item from ArrayList
  3. Clear ArrayList
  4. Count Items
  5. Sort the ArrayList Items
  6. Reverse Sort the Items
  7. Insert Item at a given location
  8. Use Binary Search to Find a Item
  9. Convert to An Array
  10. Check if Item exist in ArrayList
  11. Find Index of an Item

ASP.NET Script:

So let’s start with the ASP.NET Script. The below script have some asp.net controls to demonstrate the functionality of ArrayList.

  1. One ListBox to Display Data
  2. A textbox for Criteria and a label to display interactive messages.
  3. Multiple buttons to perform operations.

Listing 1: ASP.NET Script

<head runat="server">
    <title>MrBool.com Tutorials - ArrayList</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ListBox BackColor="#CCCCFF" ID="lstYears" runat="server" Height="255px" Width="271px">
        </asp:ListBox>
        <br />
        <br />
        Criteria:
        <asp:TextBox ID="txtCriteria" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
    </div>
    <br />
    <br />
    <asp:Button runat="server" ID="btnReload" Text="Reload" OnClick="btnReload_Click" />
     <asp:Button runat="server" ID="btnAdd" Text="Add" OnClick="btnAdd_Click" />
     <asp:Button runat="server" ID="btnDelete" Text="Delete" OnClick="btnDelete_Click" />
     <asp:Button runat="server" ID="btnClear" Text="Clear" OnClick="btnClear_Click" />
     <br />
    <asp:Button runat="server" ID="btnCount" Text="Count" OnClick="btnCount_Click" />
     <asp:Button runat="server" ID="btnSort" Text="Sort" OnClick="btnSort_Click" />
     <asp:Button runat="server" ID="btnReverse" Text="Reverse" OnClick="btnReverse_Click" />
     <asp:Button runat="server" ID="btnInsert" Text="Insert" OnClick="btnInsert_Click" />
    <br />
    <asp:Button runat="server" ID="btnBinarySearch" Text="Binary Search" OnClick="btnBinarySearch_Click" />
     <asp:Button runat="server" ID="btnToArray" Text="Convert To Array" OnClick="btnToArray_Click" />
    <br />
    <asp:Button runat="server" ID="btnContains" Text="Contains" OnClick="btnContains_Click" />
    <asp:Button runat="server" ID="btnIndex" Text="Find Index" OnClick="btnIndex_Click" />
    </form>
</body> 
 Initial Data in ArrayList

Figure 1: Initial Data in ArrayList

C# Code:

The following namespaces required in this demonstration:

Listing 2: NameSpace Used

using System;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Collections;

The first thing you have to do is to define the ArrayList and initialize it. Define a global ArrayList, so that you can use it from different locations.

static ArrayList YearArray;

To initialize this ArrayList use the following code:

YearArray = new ArrayList();

To Fill the ArrayList and display in ListBox Use the Following Function:

Listing 3: Sample Data Used in Demonstration

private void FillArrayList()
    {
        YearArray = new ArrayList();
        YearArray.Add("Year - 2010");
        YearArray.Add("Year - 2011");
        YearArray.Add("Year - 2012");
        YearArray.Add("Year - 2013");
        YearArray.Add("Year - 2014");
        YearArray.Add("Year - 2015");
        YearArray.Add("Year - 2016");
        YearArray.Add("Year - 2017");
        YearArray.Add("Year - 2018");
        YearArray.Add("Year - 2019");
        YearArray.Add("Year - 2020");
    }

Add Item to ArrayList:

To Add the item in ArrayList use the Add method of ArrayList. The add method take argument as object type that’s why it support multi data type.

Add Item - Year - 2022

Figure 2: Add Item - “Year - 2022”

Listing 4: Add Item in ArrayList

protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (txtCriteria.Text.Trim() != "")
        {
            YearArray.Add(txtCriteria.Text.Trim());
            lstYears.DataSource = YearArray;
            lstYears.DataBind();
            lblMessage.Text = "ArrayList Item Added";
        }
        else
        {
            lblMessage.Text = "Please Enter an Item to Add";
        }
    }

Delete Item from ArrayList:

Use Remove method to delete item from ArrayList. Remove method accept the object type argument and delete from ArrayList. Note that after deleting element from ArrayList you have to add is back to ListBox.

Delete Item - Year - 2017

Figure 3: Delete Item - “Year - 2017”

Listing 5: Delete Item from ArrayList

protected void btnDelete_Click(object sender, EventArgs e)
    {
        if (txtCriteria.Text.Trim() != "")
        {
            if (YearArray.Contains(txtCriteria.Text.Trim()))
            {
                YearArray.Remove(txtCriteria.Text.Trim());
                lstYears.DataSource = YearArray;
                lstYears.DataBind();

                //YearArray.RemoveAt(1);
                lblMessage.Text = "ArrayList Item Deleted";
            }
            else
            {
                lblMessage.Text = "Item Not Found.";
            }
        }
        else
        {
            lblMessage.Text = "Please Enter an Item to Delete";
        }

    }

Clear ArrayList:

To clear the items from ArrayList just call the Clear() method of ArrayList and it will remove all items from it.

Listing 6: Clear All Items from ArrayList

protected void btnClear_Click(object sender, EventArgs e)
    {
        YearArray.Clear();
        lstYears.DataSource = YearArray;
        lstYears.DataBind();
        lblMessage.Text = "ArrayList Items Cleared";
    }

Count Items:

C# provides inbuilt property to count the number of items in ArrayList. Use Count Property to find the total count.

Item Count

Figure 4: Item Count

Listing 7: Count ArrayList Items

protected void btnCount_Click(object sender, EventArgs e)
    {
        int intCount = YearArray.Count;
        lblMessage.Text = "ArrayList Items Count:" + intCount;
    }

Sort the ArrayList Items:

ArrayList do not sort items by default, so you have to call Sort() method separately to sort the values. Sort Items in Ascending Order

Figure 5: Sort Items in Ascending Order

Listing 8: Sort ArrayList Items

protected void btnSort_Click(object sender, EventArgs e)
    {
        YearArray.Sort();
        lstYears.DataSource = YearArray;
        lstYears.DataBind();
        lblMessage.Text = "ArrayList Items Sorted";
    }

Reverse Sort the Items:

Sort method sort the values in ascending order, to sort in descending order use Reverse() method.

Sort Items in Descending Order

Figure 6: Sort Items in Descending Order

Listing 9: Reverse Sort ArrayList Items

protected void btnReverse_Click(object sender, EventArgs e)
    {
        YearArray.Reverse();
        lstYears.DataSource = YearArray;
        lstYears.DataBind();
        lblMessage.Text = "ArrayList Items Reversed";
    }

Insert Item at a given location:

To insert a value at given location pass the index and the value. After calling this method the value will be inserted in specified place.

Listing 10: Insert Item in ArrayList

protected void btnInsert_Click(object sender, EventArgs e)
    {
        if (txtCriteria.Text.Trim() != "")
        {
            YearArray.Insert(0, txtCriteria.Text.Trim());
            lstYears.DataSource = YearArray;
            lstYears.DataBind();
            lblMessage.Text = "ArrayList Item Inserted";
        }
        else
        {
            lblMessage.Text = "Please Enter an Item to Insert";
        }
    }

Use Binary Search to Find an Item:

Binary Search is efficient while searching on large and sorted data. So if your ArrayList is sorted you can use the Binary Search for more efficient results.

Listing 11: Perform Binary Search on ArrayList

protected void btnBinarySearch_Click(object sender, EventArgs e)
    {
        if (txtCriteria.Text.Trim() != "")
        {
            int Index = YearArray.BinarySearch(txtCriteria.Text.Trim());
            if (Index > 0)
                lblMessage.Text = "Item Found in Binary Search";
            else
                lblMessage.Text = "Item Not Found in Binary Search";
        }
        else
        {
            lblMessage.Text = "Please Enter an Item to Binary Search";
        }
    }

Convert ArrayList to An Array:

The C# provides inbuilt functionality to convert a given ArrayList into Array. Use ToArray() method to achieve the same.

Listing 12: Obtain Array from ArrayList

protected void btnToArray_Click(object sender, EventArgs e)
    {
        object[] strYear = YearArray.ToArray();
        if (strYear != null && strYear.Count() > 0)
            lblMessage.Text = "ArrayList Converted in Array.";

    }

Check if Item exists in ArrayList:

To check that a particular item exist in ArrayList or not use the Contains() method and pass the value.

Listing 13: Find if Item Exist

protected void btnContains_Click(object sender, EventArgs e)
    {
        if (txtCriteria.Text.Trim() != "")
        {
            if (YearArray.Contains(txtCriteria.Text.Trim()))
            {
                lblMessage.Text = "ArrayList Item Found";
            }
            else
            {
                lblMessage.Text = "ArrayList Item Not Found.";
            }
        }
        else
        {
            lblMessage.Text = "Please Enter an Item to Delete";
        }
    }

Find Index of an Item:

If you would like to find out an index of given item the use the IndexOf() method.

Find index of an Item - Year - 2014

Figure 7: Find index of an Item - “Year - 2014”

Listing 14: Find the index of Item

protected void btnIndex_Click(object sender, EventArgs e)
    {
        if (txtCriteria.Text.Trim() != "")
        {
            if (YearArray.IndexOf(txtCriteria.Text.Trim()) > 0)
            {
                lblMessage.Text = "ArrayList Item Found at Index: " + YearArray.IndexOf(txtCriteria.Text.Trim());
            }
            else
            {
                lblMessage.Text = "ArrayList Item Not Found.";
            }
        }
        else
        {
            lblMessage.Text = "Please Enter an Item to Delete";
        }
    }

I hope this tutorial is useful for you and giving you some practical knowledge of ArrayList.



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