Sunday, July 25, 2010

Creating Using Dynamic Array's in Asp.Net C# VB.Net

In some cases developers need to use dynamic arrays in Asp.net. But it’s not straight forward as like VB. If you were a VB developer then you knew that for dynamic array's VB uses REDIM keyword to generate dynamic array's. Here in this post i will discuss how developer can use dynamic arrays in asp.net pages. Basically there is no straight forward way to use but you can achieve the dynamic size by using a collection named ArrayList. The ArrayList collection provide us to add any type of object (int, float, string, object, collection, user defined datatype) in its index by using ADD() method and by using count method we will know how many object the ArrayList currently hold. So let’s go for an example on dynamic arrays in both C# and VB.Net.


CLICK HERE to read How to convert ArrayList  to Array.




C# Dynamic Array Example:
using System;
using System.Collections;

public partial class Dynamic_Array : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ArrayList Dynamic_List = new ArrayList();
       
        for(int i=0; i<5; i++)
            Dynamic_List.Add(i);

        Dynamic_List.Add("You can put Object/any datatype here !!");

        for (int i = 0; i < Dynamic_List.Count; i++)
            Response.Write("Index " + i.ToString() + ": " + Dynamic_List[i].ToString() + "</br>");
    }
}

VB.Net Dynamic Array Example:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim Dynamic_List As New ArrayList()
        Dim i As Integer

        For i = 0 To 5
            Dynamic_List.Add(i)
        Next i

        Dynamic_List.Add("You can put Object/any datatype here !!")

        For i = 0 To Dynamic_List.Count - 1
            Response.Write("Index " + i.ToString() + ": " + Dynamic_List(i).ToString() + "</br>")
        Next i

    End Sub
End Class

Hope now you can use Dynamic array in asp.net C# VB.Net.

No comments:

Post a Comment

Write your Comment: