Table: tblCustomer columns: custId(string), custFName(string), custLName(string), Address1(string), Address2(string), City(String), Zipcode(string), State(String), email(string), Phone(string).
I want to retrieve the values of these columns: custId(string), custFName(string), custLName(string), email(string), Phone(string) from tblCustomer.
I want to change the column names to Customer Id, First Name, Last Name, Email, Phone Number in the new table.
I am able to get only one column. How to get multiple columns and all rows and convert it to a DataTable
DataTable dt = tblCustomer
.AsEnumerable()
.Select(rows => rows.Field<string>("custId").Copytodatatable()
CodePudding user response:
Call the .ToTable
method of the DataTable.DefaultView
property and pass the columns in question.
var cols = new[] { "custId", "custFName", "custLName", "email", "Phone" };
var dt = tblCustomer.DefaultView.ToTable(false, cols);
Or
var dt = tblCustomer.DefaultView.ToTable(false,
"custId", "custFName", "custLName", "email", "Phone");
To name the new DataTable
, use an overload that takes the tableName
param.
var dt = tblCustomer.DefaultView.ToTable("Customer", false,
"custId", "custFName", "custLName", "email", "Phone");
To rename the column captions, assign new caption to the DataColumn.Caption
property of each column.
var dt = tblCustomer.DefaultView.ToTable("Customer", false,
"custId", "custFName", "custLName", "email", "Phone");
dt.Columns["custId"].Caption = "Customer Id";
dt.Columns["custFName"].Caption = "First Name";
dt.Columns["custLName"].Caption = "Last Name";
// ...etc.