0
votes

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

3
Do you actually need the Home column between the query and when you want the column removing? If not, why not just select the columns in the SELECT statement rather than them all with the asteriskhorHAY
Thanks for your comment. This is really small piece of my code. So I need to remove specific column. this is not only for one table. :)Gayan
Can't you just skip selecting it? It seems like your table already needs special treatment so maybe a generic sql select is not appropriate.Mattias Nordqvist
Ok, so what if you create a new datatable and copy your data over to the new one? Or maybe as Tim Schmelter suggests. :)Mattias Nordqvist
I would follow Taosique's answer, but whats the reason for removing that column anyway?horHAY

3 Answers

1
votes

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 +'"');
1
votes

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.

-1
votes

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