Jackson Lopes
Jackson Lopes

Reputation: 255

Filtering columns in datatable

I have a datatable with multiple columns. I want to filter the columns for which i do:

newDatableName= OldDt.ToTable(false,"col1","col2");

Now suppose, I want to specify the column names dyanamically i.e put all the column names in a string and then Do:

string colnames= "col1,col2";
 newDatableName= OldDt.ToTable(false,colnames);

I tried the above but it does not work. I even tried:

string colname= "\"col1\",\"col2\"";

but it considers the string of column names as one column and gives the error that no such column present.

Any help appreciated.

Upvotes: 3

Views: 5999

Answers (3)

varsha
varsha

Reputation: 1620

DataTable.DefaultView.ToTable(bool, Params string[] ColumnNames);

The above Method creates and returns a new DataTable based on rows in an existing DataView.

You have to passes two parameters to this function. If true, the returned DataTable contains rows that have distinct values for all its columns. The default value is false. A string array that contains a list of the column names to be included in the returned DataTable . The DataTable contains the specified columns in the order they appear within this array. For Example:

DataTable NewTable = dt.DefaultView.ToTable(false, "StartDate", "FinishDate", "ItemName", "AssigneeNames", "ProjectName", "PercentComplete");

Upvotes: 0

Steve
Steve

Reputation: 216293

I suppose that you are using the DataView.ToTable method (so OldDT is a DataView not a DataTable).
In this case you need to pass an array of your column names

string[] colnames = new string[] {"col1", "col2"};
newDatableName= OldDt.ToTable(false,colnames);

Upvotes: 5

niceman
niceman

Reputation: 2673

you can use Steve's answer, if don't like defining a new array try this:

string colnames="col1,col2"
newDatableName=OldDt.ToTable(colnames.Split(',');

Upvotes: 1

Related Questions