none
Query and return value from DataTable RRS feed

  • Question

  • Using C# how do I query my DataTable. 

    I need to query return a specific. For example, SELECT Name WHERE ID = 1;

    OleDbDataAdapter da = new OleDbDataAdapter();

    System.Data.DataTable dt = new System.Data.DataTable();

    da.Fill(dt, Dts.Variables["User::DataObject"].Value);



    Mr Shaw... One day I might know a thing or two about SQL Server!

    Friday, November 30, 2018 1:12 PM

All replies

  • You can use Select method which returns data row collection.

    var names = dt.Select("ID = 1").Select(k=>k["Name"]);


    • Edited by Petr B Friday, November 30, 2018 1:29 PM
    Friday, November 30, 2018 1:29 PM
  • Here is another way to get one row by id.

    var id = 1;
    var row = Dts.AsEnumerable().FirstOrDefault(r => r.Field<int>("Id") == id);
    if (row != null)
    {
        // use row data e.g. 
        var name = row.Field<string>("Name");
    }


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Friday, November 30, 2018 1:38 PM
    Moderator
  • This throws and error.

    Mr Shaw... One day I might know a thing or two about SQL Server!

    Friday, November 30, 2018 2:05 PM
  • System.Data.DataTable tb = new System.Data.DataTable();
                tb.Columns.Add("Id");
                tb.Columns.Add("Name");
                for (int i = 0; i < 10; i++)
                {
                    var row = tb.NewRow();
                    row["Id"] = i;
                    row["Name"] = i.ToString();
                    tb.Rows.Add(row);
                }
                var names = tb.Select("Id = 1").Select(k => k["Name"]);
    It works.

    Friday, November 30, 2018 3:27 PM