27

I have a DataSet full of costumers. I was wondering if there is any way to filter the dataset and only get the information I want. For example, to get CostumerName and CostumerAddress for a costumer that has CostumerID = 1

Is it possible?

4
  • 1
    possible duplicate of Filtering dataset with condition Commented May 15, 2011 at 10:44
  • @Caspar Kleijne - Sorry did not see that.
    – Erika
    Commented May 15, 2011 at 10:50
  • No Problem happens to me a lot as well, anyway, your answer is in that post, hope you are helped with that ;) Commented May 15, 2011 at 10:51
  • 2
    Are the costumers members of the International Costumers' Guild, by chance? costume.org
    – RobertB
    Commented Nov 10, 2015 at 20:52

3 Answers 3

48

You can use DataTable.Select:

var strExpr = "CostumerID = 1 AND OrderCount > 2";
var strSort = "OrderCount DESC";

// Use the Select method to find all rows matching the filter.
foundRows = ds.Table[0].Select(strExpr, strSort);  

Or you can use DataView:

ds.Tables[0].DefaultView.RowFilter = strExpr;  

UPDATE I'm not sure why you want to have a DataSet returned. But I'd go with the following solution:

var dv = ds.Tables[0].DefaultView;
dv.RowFilter = strExpr;
var newDS = new DataSet();
var newDT = dv.ToTable();
newDS.Tables.Add(newDT);
4
  • @Kamyar - The thing is that I need the result for the filtering to be in DataSet format. How do I do?
    – Erika
    Commented May 15, 2011 at 10:47
  • @Erika: You can use dataview's ToTable method to convert dataview to datatable. var dv = ds.Tables[0].Defaultview; dv.RowFilter=...; var dt = dv.ToTable(); Why would you want it to be a dataset?
    – Kamyar
    Commented May 15, 2011 at 10:51
  • @Kamyar - The customer wants it to be dataset :S, is it possible to convert it to DataSet again?
    – Erika
    Commented May 15, 2011 at 11:02
  • @Kamyar - Thank you very much. It works great. The only thing that iam wondering about is if its possible to edit the filtering so that only two columns in the dataset shown and not all of the columns. I only nead CustomerName and CustomerAdress. How can I filter the columns to?
    – Erika
    Commented May 16, 2011 at 9:23
6

No mention of Merge?

DataSet newdataset = new DataSet();

newdataset.Merge( olddataset.Tables[0].Select( filterstring, sortstring ));
1

The above were really close. Here's my solution:

Private Sub getDsClone(ByRef inClone As DataSet, ByVal matchStr As String, ByRef outClone As DataSet)
    Dim i As Integer

    outClone = inClone.Clone
    Dim dv As DataView = inClone.Tables(0).DefaultView
    dv.RowFilter = matchStr
    Dim dt As New DataTable
    dt = dv.ToTable
    For i = 0 To dv.Count - 1
        outClone.Tables(0).ImportRow(dv.Item(i).Row)
    Next
End Sub

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.