C# DataTable

DataTable class creates a table of rows and columns.

using System.Data;
DataTable dt = new DataTable("age");
DataColumn col_name = new DataColumn("name", System.Type.GetType("System.String"));
DataColumn col_zip = new DataColumn("age", System.Type.GetType("System.Int32"));
dt.Columns.Add(col_name);
dt.Columns.Add(col_zip);
DataRow row = dt.NewRow();
row["name"] = "Mary";
row["age"] = 28;
dt.Rows.Add(row);
DataRow row2 = dt.NewRow();
row2["name"] = "John";
row2["age"] = 32;
dt.Rows.Add(row2);

Loop through a DataTable.
foreach (DataRow rw in dt.Rows)
{
object name = rw[0];
object age = rw[1];
Console.WriteLine(name.ToString() + "," + age.ToString());
}
//results:
Mary,28
John,32

Select method search through the DataTable.
DataRow[] arr = dt.Select("name='John'");
foreach (DataRow rw in arr)
{
object name = rw[0];
object age = rw[1];
Console.WriteLine(name.ToString() + "," + age.ToString());
}
//John,32

Delete a row of DataTable.
dt.Rows[0].Delete();



endmemo.com © 2024  | Terms of Use | Privacy | Home