DataBinding GridView with Asp.net Array List
DataBinding is an integral part in developing GUI intensive applications. It really eases the job of populating the data into the control from respective DataSource. The DataSource is usually being an IEnumerator. Means all the objects that implement an IEnumerator can be used to bind the controls.
Though Binding a GridView is very simple task in VB.Net, the following is essential. Understanding
• how to use a DataSource
• Once the DataSource is given how to bind the data.
Why ArrayList over Array?
The reason behind I have chosen ArrayList over array is, because of the ease of use. The array needs to be re dim every time when the number of elements is changed. If you want to add a new item then you have to re dim the array.
But ArrayList are much easier to work with. The reason behind is, it is something like collection in Classic VB. You can add, remove the items easily. There is absolutely no need to worry about the count of items. As a new item will be added, removed and the count will be calculated automatically
Since the GridView natively supports the sorting, I tried to sort the ArrayList and rebind again. This is really much easier. Call the sort method of the ArrayList and assign the DataSource again and call the DataBind. That’s it the GridView will be sorted.
Mark up (Aspx)
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb"
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<form id="form1" runat="server">
<asp:GridView runat="server" ID="GridView1" AllowSorting="true">
Partial Class _Default
Private Property ArrayDataSource() As ArrayList
Return DirectCast(ViewState("ArrayDataSource"), ArrayList)
Set(ByVal value As ArrayList)
ViewState("ArrayDataSource") = value
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
If (Not IsPostBack) Then
ArrayDataSource = GetArrayList()
Private Function GetArrayList() As ArrayList
Dim Output As New ArrayList
Dim RandomNumbers As New Random()
For RowIndex = 1 To 10
Protected Sub GridView1_Sorting(ByVal sender As Object, _
ByVal e As GridViewSortEventArgs) Handles GridView1.Sorting
Private Sub LoadData()
GridView1.DataSource = ArrayDataSource