SoFunction
Updated on 2025-03-07

C# implements the need several columns from the DataTable with multiple columns

This article describes the C# method to obtain the required columns from the DataTable with multiple columns. Share it for your reference, as follows:

Method 1:

It is also a well-known type:

("Column Name");

But this situation is only suitable for removing few columns.

If there are many columns but I only have one or two columns, then I have to use method two.

Method 2:

Copy the codeThe code is as follows:
DataTable dat = (false, new string[] { "The column name you want", "The column name you want" });

Add dataTable operation related content:

Some operations on DataTable

The easiest thing to think of in dataTable is to use a for loop to operate, but in fact, you will not use a form loop unless you have to, because the efficiency is generally not high.

1) Take the line

Rowfilter is generally used to take rows

DataTable datSource;//Data source table//Filter tableDataView davTemp = new DataView(datSource, "Filter Conditions", "Sorting Fields", DataViewRowState.Various state);
// Assign the filtered table to the new tableDataTable datNew = ();

2) Take a certain column or multiple columns of the table

DataTable datSource;//Data source tableDataTable datNew= (false, new string[] { "Column Name", "Column Name" .....});

3) Copy the value of a row [provided that the table structure or number of columns is the same]

DataTable datSource;
DataTable datNew;
[i].ItemArray= datNew. Rows[i].ItemArray;

4) The number of table columns is the same, but the column names are different. What should I do if I want to copy the value?

To change the way of thinking, since the number of columns is the same, but the column names are different, why not change the column names?

as follows:

DataTable datSource;
DataTable datNew;
datNew= ();
["FirstColumn"].ColumnName = "YourColumnName";

5) Adjust the position of the column SetOrdinal();

DataTable dat = new DataTable();
//Add three columns("col1");
("col2");
("col3");
//Add a line of data(1,2,3);
//Put the third column to the first position["col3"].SetOrdinal(0);

I hope this article will be helpful to everyone's C# programming.