Making calls to data in a database can be expensive. There may also be times where you don’t have a database system to access. The good news is Microsoft.NET C# provides objects you may query like data.
In this Code Tip I’ll demonstrate how to use a couple of these objects called Collections. You will also learn why they are extremely useful when you need to access objects as if they were records contained in a data table.
Step 1: Create a Class
Step 2: Create a SortedList Collection
Let’s suppose on your church website you want to give people access to an online Bible resource. This code-tip assumes you’ve created a class called Book to model the books in the Bible (as illustrated in the above image). In the class you would build your books into a SortedList collection as demonstrated below:
Step 3: Create a List Collection Method
Your next step is to create another class (in this example it’s called BookData). In the class you would add a different type of collection known as an object list type, or List<T> of your Book class. You return this object list type using a GetBooks() method.
Step 4: Query a List Collection Method
Finally, you’re ready to query this method in the code-behind file of your web page. The image below the Page_Load method of our web page code-behind. From here, we can query the List<Book> method using a foreach statement, then store the results from the collection into our dropdown control on the web page.
This final screenshot shows the result of the books appearing in the dropdown menu on our web page, all done with code! No querying a database, no setting up a DB server, and the application runs even faster because we don’t have the extra tme involved making a data call.
I hope this code tip has been helpful for you, and you have learned about the value of the Collections inside of the Microsoft.NET Framework. The link below to Microsoft MSDN Online provides additional information on Generic Collections in C#. God bless and happy coding!
Speak your mind...