Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove datatable column in c#

Tags:

c#

i have an datatable with 12 columns.now i need to remove all the columns except at the position "0"

i can remove individually by specifying the columns name. but i dnt want to do that.as it is not best way to code.

is there any other i can do that

thanks

like image 867
happysmile Avatar asked Aug 10 '10 01:08

happysmile


People also ask

How to remove columns from DataTable in c#?

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.

How to delete multiple columns from DataTable in c#?

I would suggest you to create a new List<T> where T will be DatColumn. Then loop through the columns of DataTable, and add the columns you want to remove into the generic list.


1 Answers

Go backwards through the columns and remove each one. You have to go backwards to avoid an index out of range exception.

// index should include zero
for( int index=table.Columns.Count-1; index>=0; index-- )
{
   table.Columns.RemoveAt( index );
}

VB.Net Lovers:

'index should include zero
For index As Integer = table.Columns.Count - 1 To 0 Step -1
    table.Columns.RemoveAt(index)
Next
like image 65
Jerod Houghtelling Avatar answered Oct 27 '22 01:10

Jerod Houghtelling