Sunday, December 14, 2008

Foreach Statement


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:


class Program


static void Main(string[] args)


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


foreach (string Names in List)


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






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");


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


ListViewItem itm = new ListViewItem();

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





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: