No. | Title |
---|---|
1 | Datatable |
2 | Add Row to Existing DataTable |
3 | Remove Row from Existing DataTable |
4 | Update Row from Existing DataTable |
5 | Clear all Row from Existing DataTable |
// Create a new DataTable
DataTable dt = new DataTable();
// Define the columns
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
// Add some data
dt.Rows.Add(1, "John", 25);
dt.Rows.Add(2, "Jane", 30);
dt.Rows.Add(3, "Bob", 45);
// Retrieve some data
foreach (DataRow row in dt.Rows)
{
Console.WriteLine("ID: {0}, Name: {1}, Age: {2}", row["ID"], row["Name"], row["Age"]);
}
// Add a new row
DataRow newRow = dt.NewRow();
newRow["ID"] = 4;
newRow["Name"] = "Sarah";
newRow["Age"] = 28;
dt.Rows.Add(newRow);
// Remove a row
DataRow rowToRemove = dt.Rows.Find(2); // find the row with ID = 2
dt.Rows.Remove(rowToRemove);
// Update a row
DataRow rowToUpdate = dt.Rows.Find(2); // find the row with ID = 2
rowToUpdate["Name"] = "Janet"; // change the value of the Name column
rowToUpdate["Age"] = 32; // change the value of the Age column
rowToUpdate.EndEdit(); // apply the changes to the DataTable
// Clear all rows
dt.Rows.Clear();