Sunday, July 25, 2010

How to convert ArrayList to Array in Asp.net C# VB.Net

In many cases developers have to create ArrayList to achieve dyanamic array functionalities. But sometimes you may need to convert the ArrayList to an array. For example if you are wnat to trnsfer csv data to ORACLE database then if you use bindarray then the conversion is required. Otherwise you won't to insert data into oracle databse. This is only one scenario but for lot of reasons you may need such type of conversion. Here in this article i will show you how you can convert ArrayList to Array.


CLICK HERE to read how to Create Dynamic Array.







C# Code 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);

        //Convert Here
 int[] array = (int[])Dynamic_List.ToArray(typeof(int));

        for(int i=0;i<=array.GetUpperBound(0);i++)
            Response.Write(array[i].ToString()+"</BR>");
    }
}

VB.NET Code 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

        // Convert here
        Dim array() As Integer
        array = DirectCast(Dynamic_List.ToArray(GetType(Integer)), Integer())

        For i = 0 To 5
            Response.Write(array(i).ToString() + "</BR>")
        Next i

    End Sub

No comments:

Post a Comment

Write your Comment: