Working with For Loop and For Each Loop

vishalneeraj-24503
Posted by vishalneeraj-24503 under C# category on | Points: 40 | Views : 694
Today,we will learn about Use of For Loop and For Each Loop in dot net. It's very easy to use.But there is a little difference between both.

In for loop,we can iterate only integer values with any objects but in case of for each loop,we can iterate any object i.e. string,objects and so on.

We can understand it by an example:-

//Take an Arraylist and add items into it.

ArrayList arr_names = new ArrayList();
arr_names.Add("vishal");
arr_names.Add("neeraj");
arr_names.Add("rajesh");
arr_names.Add("prashant");
arr_names.Add("nitin");

//getting array index values
//1st way using for loop
for (int index = 0; index <= arr_names.Count - 1; index++)
{
Response.Write("Items are : " + arr_names[index] + "<br/>");
}

//2nd way using for each loop
foreach (string item in arr_names)
{
Response.Write("Items are : " + item + "<br/>");
}


Note :- We can take any object in for each loop instead of string in for each loop

//Take another example of Gridview and i assume that gridview has rows - iterate gridview rows

//Using for loop
if (grid_view_employee_details.Rows.Count > 0)
{
GridViewRow gvr = null;

for (int index = 0; index <= grid_view_employee_details.Rows.Count-1; index++)
{
gvr = grid_view_employee_details.Rows[index] as GridViewRow;

//find any control inside gridview
Label lbl_emp_id = (Label)gvr.FindControl("lbl_employee_id");
}
}

//Using for each loop
if (grid_view_employee_details.Rows.Count > 0)
{
foreach (GridViewRow gvr in grid_view_employee_details.Rows)
{
//find any control inside gridview
Label lbl_emp_id = (Label)gvr.FindControl("lbl_employee_id");
}
}


As we can see,in For loop,i have taken index variable which is of integer data-type to iterate through Arralist and Gridview,but in Foreach loop,it's string and Gridviewrow as objects.

So,in For each loop,we can take any objects to iterate.

Comments or Responses

Login to post response