Add, Edit & Delete Operations on DataTable in C# .NET

Introduction

In C# .NET, the DataTable class serves as a fundamental component for managing in-memory data. Whether you're dealing with a simple data set or a complex relational structure, DataTable offers a versatile solution for performing operations like adding, editing, and deleting rows with ease. In this article, we'll explore these operations in-depth using a practical example of managing employee data.

Introduction to DataTable

DataTable is part of the System.Data namespace in C# .NET and provides a tabular representation of in-memory data. It consists of rows and columns, much like a database table. This structure makes it ideal for scenarios where you need to manipulate data before persisting it to a database or displaying it in a user interface.

Creating an Employee DataTable

Let's start by defining our DataTable structure for managing employee data:

DataTable employeeTable = new DataTable("Employee");

// Define columns
employeeTable.Columns.Add("EmployeeID", typeof(int));
employeeTable.Columns.Add("Name", typeof(string));
employeeTable.Columns.Add("Position", typeof(string));
employeeTable.Columns.Add("Salary", typeof(decimal));

In this example, we have columns for EmployeeID, Name, Position, and Salary.

Adding Rows to the DataTable

To populate our DataTable with employee records, we can use the NewRow() method to create a new DataRow and then add it to the DataTable:

DataRow newRow1 = employeeTable.NewRow();
newRow1["EmployeeID"] = 1;
newRow1["Name"] = "John Doe";
newRow1["Position"] = "Software Engineer";
newRow1["Salary"] = 60000.00m;

employeeTable.Rows.Add(newRow1);

Editing Rows in the DataTable

Suppose we need to update an employee's salary. We can locate the row by its EmployeeID and modify the corresponding column value:

DataRow[] rows = employeeTable.Select("EmployeeID = 1");
if (rows.Length > 0)
{
    rows[0]["Salary"] = 65000.00m; // Update salary
}

Deleting Rows from the DataTable

If an employee leaves the company, we can remove their record from the DataTable:

DataRow[] rowsToDelete = employeeTable.Select("EmployeeID = 1");
foreach (DataRow rowToDelete in rowsToDelete)
{
    employeeTable.Rows.Remove(rowToDelete);
}

Conclusion

In this article, we've explored how to perform essential operations on a DataTable in C# .NET using an employee data example. With DataTable's flexibility and functionality, you can efficiently manage in-memory data structures for various applications, ranging from simple data manipulation tasks to more complex database interactions.

By mastering DataTable operations, you empower yourself to handle data management tasks effectively within your C# .NET applications, contributing to their robustness and scalability.