C#中如何向现有Dataset内的指定DataTable添加行?
Hey there! Let's walk through exactly how to add rows to a DataTable that's already part of an existing DataSet. I'll cover both targeting a specific table and a reusable general method to make this easier for future use.
Targeting a Specific Existing DataTable
If you know the exact name (or index) of the DataTable in your DataSet, follow these straightforward steps:
- Retrieve the target DataTable from the DataSet's
Tablescollection. - Create a new DataRow that matches the table's schema using
NewRow()—this ensures the row has all the columns your table expects, so you won't run into schema mismatches. - Assign values to the row's columns, making sure they match the column data types.
- Add the row to the table's
Rowscollection.
Example Code
// Assume your existing DataSet is named 'myDataSet' // Target the "Customers" table (replace with your actual table name) DataTable customerTable = myDataSet.Tables["Customers"]; // Create a new row with the table's pre-defined schema DataRow newCustomerRow = customerTable.NewRow(); // Populate the row with values (match your table's column names/types) newCustomerRow["CustomerID"] = "BLONP"; newCustomerRow["CompanyName"] = "Blondel père et fils"; newCustomerRow["ContactName"] = "Frédérique Citeaux"; newCustomerRow["Phone"] = "88.60.15.31"; // Add the completed row to the table customerTable.Rows.Add(newCustomerRow);
Safety Check: Ensure the Table Exists
To avoid a NullReferenceException if the table doesn't exist in the DataSet, add a quick validation check:
if (myDataSet.Tables.Contains("Customers")) { // Run the row creation/adding code above } else { throw new InvalidOperationException("The 'Customers' table does not exist in the DataSet."); }
General Reusable Method
If you need to add rows to different tables in your DataSet regularly, a generic method will save you time and reduce duplicate code. This method includes input validation, checks for existing tables/columns, and proper null value handling.
Generic Method Code
public static void AddRowToDataSetTable(DataSet dataSet, string tableName, Dictionary<string, object> columnValues) { // Validate input parameters to catch issues early if (dataSet == null) throw new ArgumentNullException(nameof(dataSet), "DataSet cannot be null."); if (string.IsNullOrWhiteSpace(tableName)) throw new ArgumentNullException(nameof(tableName), "Table name cannot be empty or null."); if (columnValues == null || columnValues.Count == 0) throw new ArgumentException("Column values cannot be null or empty.", nameof(columnValues)); // Check if the target table exists in the DataSet if (!dataSet.Tables.Contains(tableName)) throw new InvalidOperationException($"Table '{tableName}' was not found in the DataSet."); DataTable targetTable = dataSet.Tables[tableName]; DataRow newRow = targetTable.NewRow(); // Assign values to each specified column foreach (var columnPair in columnValues) { string columnName = columnPair.Key; object columnValue = columnPair.Value; // Verify the column exists in the table if (targetTable.Columns.Contains(columnName)) { // Use DBNull.Value for null values to match DataTable's expected format newRow[columnName] = columnValue ?? DBNull.Value; } else { throw new ArgumentException($"Column '{columnName}' does not exist in table '{tableName}'."); } } // Add the fully populated row to the table targetTable.Rows.Add(newRow); }
How to Use the Generic Method
Call it with your DataSet, target table name, and a dictionary mapping column names to their values:
// Prepare the data for the new row var orderData = new Dictionary<string, object> { { "OrderID", 10482 }, { "CustomerID", "BLONP" }, { "OrderDate", new DateTime(2024, 5, 15) }, { "Freight", 24.67 } }; // Add the row to the "Orders" table in your DataSet AddRowToDataSetTable(myDataSet, "Orders", orderData);
Key Notes to Remember
- Type Matching: Always ensure the values you assign match the data type of the DataTable's columns (e.g., don't pass a string to an integer column—this will throw a type mismatch exception).
- Null Values: Use
DBNull.Valueinstead ofnullfor columns that allow nulls—this is required for proper DataTable compatibility. - Constraints: If your DataTable has primary key or unique constraints, double-check that the new row's values don't violate these rules (otherwise you'll get a constraint violation exception).
内容的提问来源于stack exchange,提问作者sam

