Filtering table

  • Thread starter Thread starter Predrag
  • Start date Start date
P

Predrag

Hello.

I have a DataTable variable dt and I want to create another instance of
DataTable class - dt2, that will contain:

1. only the rows from dt that meet a criteria strCriteria
2. only the columns from the list of columns columns[]/columns()

I don't want to return DataView or DataRow[]/DataRow(), but DataTable
object.

Any advice about this is very appreciated.
Thanks in advance.
- Predrag.
 
Hi. I created something similar, which I modified for you (without error checking - probably want to check that columns exist in OriginalTable before adding to NewTable, and you would also need to check if any of the columns was an expression column and modify the code which adds the column to NewTable accordingly).

NB This is not the only way to do this, but shd get you starte

public DataTable GetTable(DataTable OriginalTable,string Criteria, DataColumn[] ColumnsToInclude

// create the return tabl
DataTable NewTable=new DataTable()
for(int x=0;x<ColumnsToInclude.Length;++x
NewTable.Columns.Add(ColumnsToInclude[x].ColumnName,ColumnsToInclude[x].DataType)

// get filtered row
DataView vw=new DataView(OriginalTable)
vw.RowFilter=Criteria

// add record
foreach(DataRowView row in vw

DataRow newrow=NewTable.NewRow()
foreach(DataColumn col in NewTable.Columns

newrow[col]=row[col.ColumnName]

NewTable.Rows.Add(newrow)


// retur
return NewTable
}
 
Thanks Kevin.

I was afraid I'd have to do something like that but didn't want to make any
conclusions after couple of hours browsing MSDN and ADO.NET books. I thought
that I was missing something simple.
But, I guess you were thinking about it longer than I was, and if you came
up with this solution, than probably there is no simple solution for it.
Usually, when I end up with complex solution for something simple, I start
asking myself, is it maybe that I didn't understand framework correctly,
started using it in a way different from what its inventors intended and
went deep into trouble because of that.

Thanks a lot.
- Predrag.
 
no problem. maybe someone will post a simpler way. if they do we both learn something

kevi
 
Back
Top