Complete Guide to Adding New DataRow to DataTable in C#

Nov 23, 2025 · Programming · 9 views · 7.8

Keywords: C# | DataTable | DataRow | Data Binding | ADO.NET

Abstract: This article provides an in-depth exploration of the correct methods for adding new DataRow objects to DataTable in C#, with a focus on the Rows.Add method's usage scenarios and implementation principles. Through comparative analysis of common error patterns and standard solutions, it thoroughly examines the data binding mechanisms between DataTable, DataRow, and DataGridView, offering comprehensive code examples and best practice recommendations. The discussion extends to data validation, exception handling, and performance optimization, providing developers with complete mastery of DataTable manipulation techniques.

Fundamental Concepts of DataTable and DataRow

In C#'s ADO.NET architecture, DataTable represents an in-memory data table, while DataRow corresponds to individual rows within that table. When DataTable is bound to UI controls like DataGridView, data operations must follow specific synchronization mechanisms.

Common Error Analysis

A typical issue developers encounter is creating a DataRow object and setting field values, but the DataGridView fails to display the new row. This usually occurs because only the NewRow() method is called to create the row object, without actually adding it to the DataTable's row collection.

Error example code:

DataRow row = table.NewRow();
for (int i = 0; i < 28; i++)
{
    row[i] = i.ToString();
}
// Missing table.Rows.Add(row) call

Standard Solution

The correct approach involves using the DataRowCollection.Add method to add the newly created DataRow to the DataTable:

DataTable table = new DataTable();
DataRow row = table.NewRow();

// Set row data
row["Column1"] = "Value1";
row["Column2"] = "Value2";

// Critical step: Add row to table
table.Rows.Add(row);

Implementation Principles Deep Dive

The NewRow() method creates a new DataRow object with the same schema as the DataTable, but at this stage the row is not yet part of the table. Only when Rows.Add() is called does the row become formally added to the table's row collection, triggering relevant event notifications.

In data binding scenarios, when DataTable is bound to DataGridView through BindingSource or directly, the Rows.Add method automatically notifies the bound control to update its display. This mechanism ensures real-time synchronization between the UI and data model.

Complete Example Code

Below is a complete console application example demonstrating how to create a DataTable, define column structure, and add multiple rows of data:

using System;
using System.Data;

class Program
{
    static void Main()
    {
        // Create DataTable and define columns
        DataTable employeeTable = new DataTable("Employees");
        employeeTable.Columns.Add("ID", typeof(int));
        employeeTable.Columns.Add("Name", typeof(string));
        employeeTable.Columns.Add("Department", typeof(string));
        employeeTable.Columns.Add("Salary", typeof(decimal));

        // Add first row of data
        DataRow row1 = employeeTable.NewRow();
        row1["ID"] = 1;
        row1["Name"] = "John Smith";
        row1["Department"] = "Engineering";
        row1["Salary"] = 8000.00m;
        employeeTable.Rows.Add(row1);

        // Add second row of data
        DataRow row2 = employeeTable.NewRow();
        row2["ID"] = 2;
        row2["Name"] = "Jane Doe";
        row2["Department"] = "Sales";
        row2["Salary"] = 6000.00m;
        employeeTable.Rows.Add(row2);

        // Output table contents
        foreach (DataRow row in employeeTable.Rows)
        {
            Console.WriteLine($"ID: {row["ID"]}, Name: {row["Name"]}, Department: {row["Department"]}, Salary: {row["Salary"]}");
        }
    }
}

Data Validation and Exception Handling

In practical applications, adding DataRow requires consideration of data validation and exception handling:

try
{
    DataRow newRow = table.NewRow();
    
    // Set field values
    newRow["RequiredField"] = GetRequiredValue();
    newRow["OptionalField"] = GetOptionalValue();
    
    // Data validation
    if (string.IsNullOrEmpty(newRow["RequiredField"] as string))
    {
        throw new ArgumentException("Required field cannot be empty");
    }
    
    table.Rows.Add(newRow);
    Console.WriteLine("Row added successfully");
}
catch (Exception ex)
{
    Console.WriteLine($"Error adding row: {ex.Message}");
}

Performance Optimization Recommendations

For scenarios requiring bulk addition of numerous rows, consider the following optimization strategies:

// Method 1: Use BeginLoadData and EndLoadData
table.BeginLoadData();
try
{
    for (int i = 0; i < 1000; i++)
    {
        DataRow row = table.NewRow();
        row["Index"] = i;
        row["Data"] = $"Sample Data {i}";
        table.Rows.Add(row);
    }
}
finally
{
    table.EndLoadData();
}

// Method 2: Use LoadDataRow (if applicable)
// This method may offer better performance in certain scenarios

Integration with DataGridView

When DataTable is bound to DataGridView, adding new rows automatically reflects in the UI:

// Assuming dataGridView1 is bound to employeeTable
private void AddNewEmployee(string name, string department, decimal salary)
{
    DataRow newRow = employeeTable.NewRow();
    newRow["ID"] = GetNextEmployeeID();
    newRow["Name"] = name;
    newRow["Department"] = department;
    newRow["Salary"] = salary;
    
    employeeTable.Rows.Add(newRow);
    // DataGridView automatically updates to show new row
}

Conclusion

Properly adding DataRow to DataTable requires two critical steps: first, use the NewRow() method to create the row object and set field values, then call the Rows.Add() method to formally add the row to the table. This pattern ensures data integrity and proper UI synchronization, representing a fundamental yet crucial technique in C# data manipulation.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.