-->

Saturday, April 19, 2014

How to get last index of 2D array in c# ASP.NET

How to get last index of 2D array in c# ASP.NET

Suppose you have 2D array in the form of x and y axis, You want to access last index of both axis. Now at this time, you can consider x as row and y as column. Here we use GetUpperBound ( ) method for accessing last index of array. Lets take an example, in which we will pass 0 and 1 in the GetUpperBound ( ) method. Here 0 for first axis and 1 for second axis.
<form id="form1" runat="server">
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Clike"
        BackColor="#99CCFF" />
    <div>
   
        <asp:Label ID="Label1" runat="server" BackColor="Yellow"></asp:Label>
   
    </div>
    </form>

Code Behind
protected void Button1_Click(object sender, EventArgs e)
    {
        {
            string[,] fruits = new string[4, 2]
        {
            {"Red","Apple"},
            {"Orange","Orange"},
            {"Yellow","Banana"},
            {"Green","Mango"},          
        };
            int rows = fruits.GetUpperBound(0);            
            int columns = fruits.GetUpperBound(1);
            Label1.Text = "index of last element of first dimension [0] in fruits array: " + rows.ToString();
            Label1.Text += "<br />index of last element of second dimension [1] in fruits array: " + columns.ToString();
            Label1.Text += "<br /><br />two dimension fruits array elements.........<br />";
            for (int currentRow = 0; currentRow <= rows; currentRow++)
            {
                for (int currentColumn = 0; currentColumn <= columns; currentColumn++)
                {
                    Label1.Text += fruits[currentRow, currentColumn] + " ";
                }
                Label1.Text += "<br />";
            }
        }
Code Generate the following output
How to get last index of 2D array in c# ASP.NET


Read other related articles

Also read other articles

© Copyright 2013 Computer Programming | All Right Reserved