In this article, we are going to see, select specific columns from datatable in c#
DataTable table = new DataTable("Employees");
table.Columns.Add(new DataColumn("Id", typeof(int)));
table.Columns.Add(new DataColumn("Name", typeof(string)));
table.Columns.Add(new DataColumn("Email", typeof(string)));
table.Columns.Add(new DataColumn("Salary", typeof(decimal)));
table.Columns.Add(new DataColumn("Age", typeof(int)));
table.Rows.Add(1, "A", "abc@gmail.com", 95000, 30);
table.Rows.Add(2, "B", "pqr@gmail.com", 96000, 31);
table.Rows.Add(3, "C", "xyz@gmail.com", 97000, 32);
string[] strcols = new[] { "Id", "Name", "Email" };
for (int i = table.Columns.Count - 1; i >= 0; i--)
{
if (!strcols.Contains(table.Columns[i].ColumnName))
{
table.Columns.Remove(table.Columns[i].ColumnName);
}
}
or:
DataTable newtable = new DataView(table).ToTable(false, strcols);
0 Comments
if you have any doubts , please let me know