Sunday, December 14, 2008

Foreach Statement

Definition:

syntax: foreach (variable1 in variable2) statement[s]

The 'foreach' loop is used to iterate through the values contained by any object which implements the IEnumerable interface. When a 'foreach' loop runs, the given variable1 is set in turn to each value exposed by the object named by variable2. As we have seen previously, such loops can be used to access array values. So, we could loop through the values of an array in the following way:

Example:1

class Program

{

static void Main(string[] args)

{

String[] List={"Hemnath","Mani","Siva","Arivu","Jagan",

"Nagendra","John","Anand"};

foreach (string Names in List)

{

Console.WriteLine("{0}", Names);

Console.ReadLine();

}

}

}


Example:2

private void Form1_Load(object sender, EventArgs e)

{

string conn = "Data Source=localhost;Initial Catalog=master;Integrated Security=True";

SqlConnection connection = new SqlConnection(conn);

SqlDataAdapter da = new SqlDataAdapter("select * from Student", connection);

DataSet ds = new DataSet();

DataTable dt = new DataTable("Student");

da.Fill(ds);

foreach (DataRow dr in ds.Tables[0].Rows)

{

ListViewItem itm = new ListViewItem();

itm.Text = Convert.ToString(dr["Name"]);

itm.SubItems.Add(Convert.ToString(dr["Name"]));

listBox1.Items.Add(itm);

}

}

Note:
The main drawback of 'foreach' loops is that each value extracted (held in the given example by the variable 'List') is read-only.

No comments: