Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

HI,

I have datatable wich stores a date in one column and a value in the other. I want to create a new datatable wich has the same format but has only the rows wich verify a criteria (only the rows are between date1 and date2 for example). Wich is the best way to do such filtering?

bye

Hernan

  • *Experts*
Posted

You can use the DataSet's merge method to import a filtered set of rows. Below is a sample on some test data.

DataSet dsSource = new DataSet();
dsSource.Tables.Add("Table1");
dsSource.Tables[0].Columns.Add("name");
dsSource.Tables[0].Rows.Add(new object[] {"a"});
dsSource.Tables[0].Rows.Add(new object[] {"b"});
dsSource.Tables[0].Rows.Add(new object[] {"c"});

DataSet dsDest = new DataSet();
dsDest = dsSource.Clone(); // Get a copy of all the table structures into dsDest.
string filter = "name = 'b'"; // This would be your date range check
DataRow[] matchingRows = dsSource.Tables[0].Select(filter);
dsDest.Merge(matchingRows);

 

This solution actually creates a whole new DataSet (dsDest) not just a datatable. I started by cloning the source DataSet which creates an exact copy of the dsSource dataset minus any data.

 

-ner

"I want to stand as close to the edge as I can without going over. Out on the edge you see all the kinds of things you can't see from the center." - Kurt Vonnegut
Posted

Another way of doing it:

 

       Dim dt As DataTable = dtOriginalTable.Clone()
       Dim rows() As DataRow = dtOriginalTable.Select("<filterCondition>")
       Dim row As DataRow
       For Each row In rows
           dt.ImportRow(row)
       Next

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...