SoFunction
Updated on 2025-03-06

C# Case of traversing datatable field names and value

Methods to traverse datatable:

DataTable dt = [0];  
foreach (DataColumn col in dt .Columns)
{
 string name=;//Get the column name of the DataColumn column object  [Number of rows][].tostring()
} 
 
foreach ( k in ) 
      {
        columnName=;
        columnType=();
      }

Supplement: C# extracts DataTable specified fields to the new DataTable method

I won't say much nonsense, let's just read the code~

   /// <summary>
    /// Return two columns of data from DataTable as a new DataTable    /// </summary>
    /// <param name="sourceDt">Source Data Table</param>    /// <param name="x">The first field that needs to be returned</param>    /// <param name="y">The first field that needs to be returned</param>    /// &lt;returns&gt;&lt;/returns&gt; 
    public static DataTable GetNewDataTable(DataTable sourceDt,string x,string y)
    {
      DataTable newTable = (false, new string[] { x, y });
      return newTable;
    }

The method is to extract two columns of data to the new DataTable according to the field name, and so on. You need to extract more columns { x, y } and add them, and the corresponding (DataTable sourceDt, string x, string y) is also added.

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.