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 ReadOnlyCollection using Csharp and ASP.NET

In this article I will cover how deal with ReadOnlyCollection. The tutorial will address the basics, creating the ReadOnlyCollection and then performing different kind of operations as Search Item, CopyTo, Loop Through and Get Index.

Introduction:

This Tutorial is part of series of collection classes. In this part, I will cover the ReadOnlyCollection . As the name implies, it is collection of items which cannot be changed.

This article will cover the following topics:

  • ASP.NET - Script
  • ReadOnlyCollection - Create Collection
  • ReadOnlyCollection - Search Item
  • ReadOnlyCollection - CopyTo
  • ReadOnlyCollection - Loop Through
  • ReadOnlyCollection - Get Index
  • ReadOnlyCollection - Other Functionality
ReadOnlyCollection Items with Messenger Data

Figure 1: ReadOnlyCollection Items with Messenger Data

ASP.NET Script:

ASP.NET is used here to display the ReadOnlyCollection data. ASP.NET page will interact with user to perform different operations on ReadOnlyCollection. The below ASP.NET page have Textbox for taking input from user, Label for displaying the messages, ListBox to show the ReadOnlyCollection data and buttons to perform different operations.

ASP.NET Listing 1: ASP.NET Script for ReadOnlyCollection Demonstration

<head runat="server">
    <title>MrBool.com - ReadOnlyCollection Tutorial</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        ReadOnlyCollection Item:
        <asp:TextBox ID="txtReadOnlyCollection" runat="server"></asp:TextBox> 
        
        <br />
        <br />
        Message:
        <asp:Label ID="lblDisplay" runat="server" Text=""></asp:Label>
        <br />
        <br />
        ReadOnlyCollection State:<br />
        <asp:ListBox runat="server" ID="lstReadOnlyCollection" Width="200px" Height="150px" 
            > </asp:ListBox>
        <br />
        <br />
         <asp:Button ID="btnLooping" runat="server" Text="Looping" 
            onclick="btnLooping_Click"  />
         <asp:Button ID="btnCopyTo" runat="server" Text="CopyTo" 
            onclick="btnCopyTo_Click"  />
         <asp:Button ID="btnSearch" runat="server" Text="Search" 
            onclick="btnSearch_Click"  />
         <asp:Button ID="btnIndex" runat="server" Text="Index" onclick="btnIndex_Click" 
             />        
        
    </div>
    </form>
</body>

C# Code:

Starting with C# code, Let’s add the namespaces first, As you know that ReadOnlyCollection is also part of collection class, so we have to include the Collections.Generic namespace as well as one more namespace required here, Collections.ObjectModel. So add the following namespaces in c# code :

Listing 2: NameSpaces for List Collection

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

ReadOnlyCollection - Create Collection:

Now you have to create the ReadOnlyCollection object and initialize it like below code.

Listing 3: ReadOnlyCollection Object Declaration & Initialization along with adding the items

static ReadOnlyCollection<string> ReadOnlyMessenger;  
 
List<string> MessengerList = new List<string>();
//add the items in List
MessengerList.Add("GTalk");
MessengerList.Add("Yahoo Messenger");
MessengerList.Add("MSN Messenger");
MessengerList.Add("Facebook Messenger");
MessengerList.Add("AOL Messenger");

ReadOnlyMessenger = new ReadOnlyCollection<string>(MessengerList);

As you can see in the above code, first declare the ReadOnlyCollection object. Then Create a List of string type and add the items. In this case we have taken the messenger data. After having a list with items, Create a new ReadOnlyCollection object by passing the List into ReadOnlyCollection constructor. It will automatically create a ReadOnlyCollection object from a given List.

ReadOnlyCollection - Search Item:

ReadOnlyCollection Provide search functionality by calling the method Contains(). Pass the desire string into this method and it will return the true if value found otherwise will return false.

In this case, program is taking the input from user through the ASP.NET Textbox and then after performing the trim operation, passing the value into method. Note that Trim() method remove the blank characters from both sides.

Search Item - An item found(msn messenger)

Figure 2: Search Item - An item found (“MSN Messenger”)

Listing 4: ReadOnlyCollection - Search Item - C# Code
protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (txtReadOnlyCollection.Text.Trim() != "")
        {
            if (ReadOnlyMessenger.Contains(txtReadOnlyCollection.Text.Trim()))
            {
                lblDisplay.Text = "ReadOnlyCollection Item Found";
            }
            else
            {
                lblDisplay.Text = "ReadOnlyCollection Item Not Found.";
            }
        }
        else
        {
            lblDisplay.Text = "ReadOnlyCollection - Please Enter an Item to Search";
        }
        
    }
 

ReadOnlyCollection - CopyTo:

ReadOnlyCollection also provide a CopyTo() method to copy the items into a given array . The below code copy all the items from ReadOnlyCollection to an Array. You can specify the starting index of array. For example you specified that copy items from index 1, it means place the items in array from index 1.

ReadOnlyCollection is Converted in Array

Figure 3: ReadOnlyCollection is Converted in Array

Listing 5: ReadOnlyCollection to Array Conversion- Code

protected void btnCopyTo_Click(object sender, EventArgs e)
    {
        string[] strArray = new string[ReadOnlyMessenger.Count+2];
        ReadOnlyMessenger.CopyTo(strArray, 1);

        foreach (string ArrayItems in strArray)
        {
            lblDisplay.Text += "," + ArrayItems;
        }

        lblDisplay.Text = lblDisplay.Text.TrimStart(',');

    }
 

ReadOnlyCollection - Loop Through:

Just like other collections, ReadOnlyCollection provide compatibility with foreach loop. It means by using the foreach loop you can go through all the elements of the ReadOnlyCollection.

ReadOnlyCollection - Loop through all the items

Figure 4: ReadOnlyCollection - Loop through all the items

Listing 6: ReadOnlyCollection - foreach loop example

protected void btnLooping_Click(object sender, EventArgs e)
    {
        // Loop through ReadOnlyCollection.
        foreach (string MessengerItems in ReadOnlyMessenger)
        {
            lblDisplay.Text += "," + MessengerItems;
        }

        lblDisplay.Text = lblDisplay.Text.TrimStart(',');
    }

ReadOnlyCollection - Get Index:

ReadOnlyCollection provide a IndexOf() method to search an item in collection object and return the index.

For Example the below figure is searching for “Facebook Messenger” and it’s found at index-3. Note that ReadOnlyCollection also starts at 0.

Find Facebook Messenger in ReadOnlyCollection

Figure 5: Find “Facebook Messenger “in ReadOnlyCollection

Listing 7: ReadOnlyCollection - IndexOf - Code

protected void btnIndex_Click(object sender, EventArgs e)
    {
        if (txtReadOnlyCollection.Text.Trim() != "")
        {
            int intIndex = ReadOnlyMessenger.IndexOf(txtReadOnlyCollection.Text.Trim());
            if (intIndex > -1)
            {
                lblDisplay.Text = "ReadOnlyCollection Item Found - " + intIndex;
            }
            else
            {
                lblDisplay.Text = "ReadOnlyCollection Item Not Found.";
            }
        }
        else
        {
            lblDisplay.Text = "ReadOnlyCollection - Please Enter an Item to Search";
        }
    }

ReadOnlyCollection - Other Functionality:

ReadOnlyCollection also provide total count of items by providing the Count property.Use this and at any given point of time can know that total items in ReadOnlyCollection.

Listing 8: ReadOnlyCollection - Count the number of items

private void OtherFunctionality()
    {
        lblDisplay.Text = " Count of All the Items of ReadOnlyCollection: " + ReadOnlyMessenger.Count;              

    }

Conclusion:

This tutorial covered the ReadOnlyCollection of type string. Similarly you can have any type of ReadOnlyCollection. Create a different type of list and then create a ReadOnlyCollection. ReadOnlyCollection is just a wrapper above List, So you can still change the ReadOnlyCollection items by changing the List items.

Try source code given with this tutorial and comment here if you have any questions.



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