16

my datatable;

    dtData

    ID | ID2
    --------
    1  |  2
    1  |  3


dtData.Select("ID = 1"); one more rows;

i want row "ID = 1 And ID2 = 3" how to make ?

6 Answers 6

33

Do you mean like this?:

dtData.Select("ID=1 AND ID2=3");
0
13

Okay, here is how I do such things...

    GridFieldDAO dao = new GridFieldDAO();
    //Load My DataTable
    DataTable dt = dao.getDT();
    //Get My rows based off selection criteria
    DataRow[] drs = dt.Select("(detailID = 1) AND (detailTypeID = 2)");
    //make a new "results" datatable via clone to keep structure
    DataTable dt2 = dt.Clone();
    //Import the Rows
    foreach (DataRow d in drs)
    {
        dt2.ImportRow(d);
    }
    //Bind to my new DataTable and it will only show rows based off selection 
    //criteria
    myGrid.DataSource = dt2;
    myGrid.DataBind();

Notice in my Select() I put the criteria in Parens between AND and OR

Hope this helps! Mike V

2
  • 3
    This is a better solution than throwing a DataRow[] around. If your filter happens to return no rows, and you need the schema somewhere deep in your code, you're not going to get it from an empty array!
    – mo.
    Commented Sep 20, 2012 at 20:32
  • Which namespace has GridFieldDAO? or isn't this available to winforms?
    – PandaNL
    Commented Aug 26, 2013 at 11:15
6

Better use this :

GridFieldDAO dao = new GridFieldDAO();
//Load My DataTable
DataTable dt = dao.getDT();
//Get My rows based off selection criteria and copy them directly to datatable
DataTable dt2 = dt.Select("(detailID = 1) AND (detailTypeID = 2)").CopyToDataTable();
2
4
DataTable dt2 = dt.Select("ID = 1").CopyToDataTable;

make sure dt has rows in it

2

Here you can copy your contents to another DataTable by using CopyToDataTable method of Linq while selecting the specific rows by filtering.

DataTable dt2 = dt.Select("state = 'FL' ").CopyToDataTable; 
1
  • You should add more detail to you answer, explain to the others why this is working.
    – pix
    Commented Oct 27, 2016 at 17:10
0

Great example and very helpful. Wanted to add one thing - if you need to select on a string use something like:

DataTable dt2 = dt.Select("state = 'FL' "); 
1
  • 1
    Error: Cannot implicitly convert type 'System.Data.DataRow[]' to 'System.Data.DataTable'
    – kleineg
    Commented Aug 18, 2015 at 12:33

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.