A DataTable
is a powerful class in the System.Data
namespace that can be used to store and manipulate tabular data in a C# program. It provides a convenient way to work with data in a structured way, and it offers a variety of methods and properties for performing common data operations.
To create a DataTable
, you can use the following code:
1 2 3 | DataTable table = new DataTable(); |
This creates an empty DataTable
object. You can then add columns to the DataTable
by using the Columns
property:
1 2 3 4 | table.Columns.Add("Name", typeof(string)); table.Columns.Add("Age", typeof(int)); |
This adds two columns to the DataTable
: one for a person’s name and one for their age. The Add
method takes two arguments: the name of the column and the data type of the column.
You can add rows to the DataTable
by using the Rows
property:
1 2 3 4 5 | table.Rows.Add("Alice", 25); table.Rows.Add("Bob", 30); table.Rows.Add("Eve", 28); |
This adds three rows to the DataTable
, each representing a person with a name and an age.
You can access the data in the DataTable
using the Rows
property and the ItemArray
property of the DataRow
class:
1 2 3 4 5 6 | foreach (DataRow row in table.Rows) { Console.WriteLine("Name: {0}, Age: {1}", row["Name"], row["Age"]); } |
This code iterates through the rows of the DataTable
and prints the name and age for each person.
The DataTable
class also provides a variety of methods and properties for sorting, filtering, and searching data, as well as for converting the data to other formats such as XML and JSON. It is a useful tool for working with data in a C# program, and it is often used in conjunction with a DataAdapter
and a DataSet
to read and write data from a database.
In addition to the methods and properties mentioned above, the DataTable
class provides several other useful features for working with data. Here are a few examples:
Sorting data
To sort the data in a DataTable
, you can use the DefaultView
property and the Sort
method:
1 2 3 | table.DefaultView.Sort = "Name ASC"; |
This sorts the data in the DataTable
by the Name
column in ascending order. You can use the DESC
keyword to sort in descending order.
Filtering data
To filter the data in a DataTable
, you can use the DefaultView
property and the RowFilter
property:
1 2 3 | table.DefaultView.RowFilter = "Age > 25"; |
This filters the data to show only rows where the Age
column is greater than 25.
Searching for data
To search for data in a DataTable
, you can use the Select
method and a filter expression:
1 2 3 | DataRow[] rows = table.Select("Name='Bob'"); |
This searches the DataTable
for rows where the Name
column is equal to “Bob” and returns an array of DataRow
objects that match the search criteria.
Converting data to other formats
To convert the data in a DataTable
to another format, such as XML or JSON, you can use the WriteXml
and WriteXmlSchema
methods to generate an XML representation of the data, or the ToJson
method to generate a JSON representation of the data:
1 2 3 4 | string xml = table.WriteXml(); string json = table.ToJson(); |
The WriteXml
method generates an XML representation of the data in the DataTable
, including the schema (structure) of the table and the data itself. The WriteXmlSchema
method generates only the schema of the table. The ToJson
method generates a JSON representation of the data in the DataTable
.
Working with a database
The DataTable
class can be used in conjunction with a DataAdapter
and a DataSet
to read and write data from a database. A DataAdapter
is a class that retrieves data from a database and stores it in a DataSet
, and a DataSet
is an in-memory cache of data that can be used to store and manipulate data from a database or other data source.
To populate a DataTable
with data from a database, you can use the Fill
method of a DataAdapter
:
1 2 3 4 5 6 7 8 9 10 | string connectionString = "..."; string queryString = "SELECT * FROM Customers"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection); adapter.Fill(table); } |
This code creates a SqlDataAdapter
object and uses it to execute a SQL query that retrieves all rows from the Customers
table. It then uses the Fill
method to populate the DataTable
with the data from the database.
To update the data in a database with the data in a DataTable
, you can use the Update
method of the DataAdapter
:
1 2 3 4 5 6 7 8 9 10 | string connectionString = "..."; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Customers", connection); SqlCommandBuilder builder = new SqlCommandBuilder(adapter); adapter.Update(table); } |
This code creates a SqlDataAdapter
object and a SqlCommandBuilder
object, and uses them to update the data in the database with the data in the DataTable
.
These are just a few examples of how to use the DataTable
class to work with data in a C# program. The DataTable
class is a powerful and versatile tool that can be used in many different contexts to store and manipulate data.
Here are a few more tips for working with DataTable
objects:
Accessing data by column name or index
You can access the data in a DataTable
by either the column name or the column index. For example, the following code accesses the value of the Age
column in the first row of the DataTable
using both the column name and the column index:
1 2 3 4 | int age1 = (int)table.Rows[0]["Age"]; int age2 = (int)table.Rows[0][1]; |
Modifying data in a DataTable
You can modify the data in a DataTable
by using the ItemArray
property of the DataRow
class. For example, the following code sets the Name
and Age
columns of the first row of the DataTable
to new values:
1 2 3 4 | table.Rows[0]["Name"] = "Charlie"; table.Rows[0]["Age"] = 35; |
You can also use the SetField
method to set the value of a specific column in a DataRow
:
1 2 3 4 | row.SetField("Name", "Charlie"); row.SetField("Age", 35); |