149

I have a DataSet which I get a DataTable from that I am being passed back from a function call. It has 15-20 columns, however I only want 10 columns of the data.

Is there a way to remove those columns that I don't want, copy the DataTable to another that has only the columns defined that I want or is it just better to iterate the collection and just use the columns I need.

I need to write the values out to a fixed length data file.

1
  • I don't have any control over the dataset I recieve. The only thing I know is that it contains everything. Commented Sep 16, 2008 at 18:10

4 Answers 4

371

Aside from limiting the columns selected to reduce bandwidth and memory:

DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);
Sign up to request clarification or add additional context in comments.

1 Comment

Just to clarify: This also works when the DataTable already has existing rows, not only on an empty DataTable.
24

To remove all columns after the one you want, below code should work. It will remove at index 10 (remember Columns are 0 based), until the Column count is 10 or less.

DataTable dt;
int desiredSize = 10;

while (dt.Columns.Count > desiredSize)
{
   dt.Columns.RemoveAt(desiredSize);
}

2 Comments

just my 2c, I don't like this solution, working with column indexes leads to nightmare maintenance..
the question includes the following statement: "..columns defined that I want.." so that means columns needed are not even necessarily in sequential order so one cannot simply say "I need the first 10 columns". As such the solution must contain an array of column names that he wants, then we can eliminate all others not falling into this "defined" set of names. Different ways to implement this; from simple foreach loop to query or linq using IN.
12

The question has already been marked as answered, But I guess the question states that the person wants to remove multiple columns from a DataTable.

So for that, here is what I did, when I came across the same problem.

string[] ColumnsToBeDeleted = { "col1", "col2", "col3", "col4" };

foreach (string ColName in ColumnsToBeDeleted)
{
    if (dt.Columns.Contains(ColName))
        dt.Columns.Remove(ColName);
}

Comments

0

How about you just select the columns you want like this:

Dim Subjects As String = "Math, English"
Dim SubjectData As DataTable = Table.AsDataView.ToTable(True, Subjects.Split(","))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.