Gayan
Gayan

Reputation: 1563

Remove DataColumn from DataTable with Data

I have Datatable with Data. I called my postgres data base and get DataTable.

// get the new data from postgres
   var dataTable = pg.GetDataTable("SELECT * FROM " + '"'+table+'"');

Now I need to remove specific Column. assume that there are 5 columns with data.

ID     |   Name   | Address | Mobile | Home
_______________________________________________
    1  |  A       |AAA      | 123    | 345
    2  |  B       |BBB      | 234    | 456
    3  |  C       |CCC      | 345    | 567

So I need to remove "Home " DataColumn and Recreate this DataTable as following

  ID   |   Name   | Address | Mobile 
____________________________________
    1  |  A       |AAA      | 123    
    2  |  B       |BBB      | 234    
    3  |  C       |CCC      | 345    

How can I do this ?

Appreciate your comments.

Thanks

Upvotes: 0

Views: 1046

Answers (3)

Basvo
Basvo

Reputation: 156

Consider using dataTable.Columns.Remove("ColumnName") or dataTable.Columns.RemoveAt(ColumnNumber)

Upvotes: -1

ttaaoossuu
ttaaoossuu

Reputation: 7894

Just specify the columns you need explicitly rather than selecting unneeded columns and removing them afterwards:

SELECT "Id", "Name", "Address", "Mobile"

Using SELECT * is bad manners because it makes your contract with database unstable - should column configuration change you will get unpredictable result.

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460288

You just need to use the method DataTable.Columns.Remove(string name):

dataTable.Columns.Remove("Home");

Then the table doesn't contain this column anymore and all rows' data in this column is thrown away. However, omit this column in the first place and list the desired columns:

var dataTable = pg.GetDataTable("SELECT ID, Name, Address, Mobile FROM " + '"'+ table +'"');

Upvotes: 1

Related Questions