C# Using Linq to Query DataTable and Bind to Gridview

Last post 06-12-2008 6:38 AM by dotnetukguru. 25 replies.

Sort Posts:

  • Re: C# Using Linq to Query DataTable and Bind to Gridview

    05-11-2008, 7:17 PM

    Hi,

    I know...but that does not apply in this case as i am not using standard tables in the database, i am using one stored procedure which returns a result set which i put in a datatable

    and which i cache now i want to query that cached datatable using linq query but when i set my gridview datasource to point to the query i get a 

      "The data source does not support server-side data paging" error so i need a way to convert the result which is stored in query back into a datable so that i can then set that to my Gridview and not get that paging error issue..so how do i do that using Linq as i dont see a way of doing this with Linq tp SQL, since i am querying a cached Datatable and not tables from aDatabase

    thanks

    This above all: to thine own self be true.

    William shakespeare, Hamlet
  • Re: C# Using Linq to Query DataTable and Bind to Gridview

    05-12-2008, 2:57 AM

    Hi I have been able to get past the first error that says my "datasource does not support Server-side paging" the issue i now have is displaying my data in the Gridview

    when i now  set the result set of the query as my datasource and bind it to to the gridview,  the gridview doesnot display any data, buti know there is data returned into the linq query around 10152 rows and 103 columns and i cross checked it with my query returned in the database so it is correct...so do i need to do anything else to see the data in the gridview, as the page returned is just blank.

    DataSet ds = (DataSet) Cache["dsResult"];

    DataTable dt = ds.Tables[0];

    //EnumerableRowCollection<DataRow> query

    var query

    = from c in dt.AsEnumerable() select new

    {

    SecurityCode = c.Field<
    string>("SecurityCode"),

    SecurityName = c.Field<string>("SecurityName"),

    Currency = c.Field<string>("Currency"),

    Product = c.Field<string>("Product"),

    CountryIssue = c.Field<string>("CountryIssue"),

    Location = c.Field<string>("Location"),

    Tag = c.Field<string>("Tag"),

    AvgBorrowCost = c.Field<decimal>("AvgBorrowCost"),

    AvgLoanCost = c.Field<decimal>("AvgLoanCost"),

    AvgBorrowRebate = c.Field<decimal>("AvgBorrowRebate"),

    AvgLoanRebate = c.Field<decimal>("AvgLoanRebate"),

    Price = c.Field<decimal>("Price"),

    SettledTotal = c.Field<decimal>("SettledTotal"),

    SettledValue = c.Field<decimal>("SettledValue"),

    PendingDate1 = c.Field<decimal>("PendingDate1"),

    PendingValue1 = c.Field<decimal>("PendingValue1"),

    NetDate1 = c.Field<decimal>("NetDate1"),

    NetValue1 = c.Field<decimal>("NetValue1"),

    PendingDate2 = c.Field<decimal>("PendingDate2"),

    PendingValue2 = c.Field<decimal>("PendingValue2"),

    NetDate2 = c.Field<decimal>("NetDate2"),

    NetValue2 = c.Field<decimal>("NetValue2"),

    PendingDate3 = c.Field<decimal>("PendingDate3"),

    PendingValue3 = c.Field<decimal>("PendingValue3"),

    NetDate3 = c.Field<decimal>("NetDate1"),

    NetValue3 = c.Field<decimal>("NetValue1"),

    //pending and net 4 to 22 here

    Total = c.Field<decimal>("Total")

    };

    //enumerate values

    //foreach (var c in query)

    //{

    // Debug.WriteLine("Contact ID: {0} Name: {1}, {2} Order ID: {3} Order date: {4:d} ",

    // c.ContactID, c.LastName, c.FirstName,

    // c.OrderID, c.OrderDate);

    //}

     

    gvPositionManager.DataSource = query;

    gvPositionManager.DataBind();

    i.e //do i need to do anything else here? please see my previous posting of the entire code above

    Gridview.Datasource = query; .e //do i need to do anything else here? please see my previous posting of the entire code above

    gridview.Databind();

     

    thanks

     

     

    This above all: to thine own self be true.

    William shakespeare, Hamlet
  • Re: C# Using Linq to Query DataTable and Bind to Gridview

    05-12-2008, 3:53 AM
    • Loading...
    • kipo
    • Joined on 07-20-2006, 7:10 AM
    • Croatia
    • Posts 1,469

    What is the ID of your GridView? If it is "gridview" than you need to change this line:

    Gridview.Datasource = query;
    into this:
    gridview.Datasource = query;
    You must be aware that C# distinguish upper / lower case.

  • Re: C# Using Linq to Query DataTable and Bind to Gridview

    05-12-2008, 6:20 AM

    Hi Kipo,

    thanks for your speedy reply i am now actually able to return  data but it takes avery long time as i have 10512 records and 103 columns,

    this is the result set of the Linq query but i have implemented paging and sorting  programmatically, hence i am handling the sorting PageindexChanging evens like so:

     

    so that it paginates in 50 rows per page

     what seems to happen is all the 10512 rows are returned...from the query which is now bound to my gridview

    could you please show me how i can then filter the data returned from my cache into the datatable, i suppose this is using a where clause on my Linq query

     

    DataSet ds = (DataSet) Cache["dsResult"]; //all 10512 rows + 103 columns

    DataTable dt = ds.Tables[0];

    //EnumerableRowCollection<DataRow> query

    var query // i think i need as where clause to filter data into the query that i will bind***

    = from c in dt.AsEnumerable() select new

    {

    SecurityCode = c.Field<
    string>("SecurityCode"),

    SecurityName = c.Field<string>("SecurityName"),

    Currency = c.Field<string>("Currency"),

    Product = c.Field<string>("Product"),

    CountryIssue = c.Field<string>("CountryIssue"),

    Location = c.Field<string>("Location"),

    Tag = c.Field<string>("Tag"),

    AvgBorrowCost = c.Field<decimal>("AvgBorrowCost"),

    AvgLoanCost = c.Field<decimal>("AvgLoanCost"),

    AvgBorrowRebate = c.Field<decimal>("AvgBorrowRebate"),

    AvgLoanRebate = c.Field<decimal>("AvgLoanRebate"),

    Price = c.Field<decimal>("Price"),

    SettledTotal = c.Field<decimal>("SettledTotal"),

    SettledValue = c.Field<decimal>("SettledValue"),

    PendingDate1 = c.Field<decimal>("PendingDate1"),

    PendingValue1 = c.Field<decimal>("PendingValue1"),

    NetDate1 = c.Field<decimal>("NetDate1"),

    NetValue1 = c.Field<decimal>("NetValue1"),

    PendingDate2 = c.Field<decimal>("PendingDate2"),

    PendingValue2 = c.Field<decimal>("PendingValue2"),

    NetDate2 = c.Field<decimal>("NetDate2"),

    NetValue2 = c.Field<decimal>("NetValue2"),

    PendingDate3 = c.Field<decimal>("PendingDate3"),

    PendingValue3 = c.Field<decimal>("PendingValue3"),

    NetDate3 = c.Field<decimal>("NetDate1"),

    NetValue3 = c.Field<decimal>("NetValue1"),

    //pending and net 4 to 22 here

    Total = c.Field<decimal>("Total")

    };

    //enumerate values

    //foreach (var c in query)

    //{

    // Debug.WriteLine("Contact ID: {0} Name: {1}, {2} Order ID: {3} Order date: {4:d} ",

    // c.ContactID, c.LastName, c.FirstName,

    // c.OrderID, c.OrderDate);

    //}

     

    gvPositionManager.DataSource = query;

    gvPositionManager.DataBind();

    This above all: to thine own self be true.

    William shakespeare, Hamlet
  • Re: C# Using Linq to Query DataTable and Bind to Gridview

    05-12-2008, 9:53 AM
    • Loading...
    • kipo
    • Joined on 07-20-2006, 7:10 AM
    • Croatia
    • Posts 1,469

    Try with this:

            var query = (from c in dt.AsEnumerable()
                        select new
                        {
                            SecurityCode = c.Field<string>("SecurityCode"),
                            SecurityName = c.Field<string>("SecurityName"),
                            Currency = c.Field<string>("Currency"),
                            Product = c.Field<string>("Product"),
                            CountryIssue = c.Field<string>("CountryIssue"),
                            Location = c.Field<string>("Location"),
                            Tag = c.Field<string>("Tag"),
                            AvgBorrowCost = c.Field<decimal>("AvgBorrowCost"),
                            AvgLoanCost = c.Field<decimal>("AvgLoanCost"),
                            AvgBorrowRebate = c.Field<decimal>("AvgBorrowRebate"),
                            AvgLoanRebate = c.Field<decimal>("AvgLoanRebate"),
                            Price = c.Field<decimal>("Price"),
                            SettledTotal = c.Field<decimal>("SettledTotal"),
                            SettledValue = c.Field<decimal>("SettledValue"),
                            PendingDate1 = c.Field<decimal>("PendingDate1"),
                            PendingValue1 = c.Field<decimal>("PendingValue1"),
                            NetDate1 = c.Field<decimal>("NetDate1"),
                            NetValue1 = c.Field<decimal>("NetValue1"),
                            PendingDate2 = c.Field<decimal>("PendingDate2"),
                            PendingValue2 = c.Field<decimal>("PendingValue2"),
                            NetDate2 = c.Field<decimal>("NetDate2"),
                            NetValue2 = c.Field<decimal>("NetValue2"),
                            PendingDate3 = c.Field<decimal>("PendingDate3"),
                            PendingValue3 = c.Field<decimal>("PendingValue3"),
                            NetDate3 = c.Field<decimal>("NetDate1"),
                            NetValue3 = c.Field<decimal>("NetValue1"),
                            //pending and net 4 to 22 here
                            Total = c.Field<decimal>("Total")
                        }).Skip(50).Take(50);
    where Skip(50) means that you want to take rows from number 50 and Take(50) means that you will return 50 rows.

  • Re: C# Using Linq to Query DataTable and Bind to Gridview

    05-12-2008, 1:15 PM

    Thanks i will give that a try and let you know

     

    kind regards

    This above all: to thine own self be true.

    William shakespeare, Hamlet
  • Re: C# Using Linq to Query DataTable and Bind to Gridview

    05-12-2008, 1:28 PM

    thank you very much! the Skip and Take()   works !!! the only thing i am not sure of now is how to retrieve the next set of  N rows, from my page as i cannot see the page navigation for getting the next set of N rows

    hence my question is do i still need to implement my Paging and Sorting  programmatically be handling the  Sorting and PageIndexChanging events to be able to sort and Page in my gridView?

    or i no longer need to do this ...at least for the paging? but i still cant see the number pages for my N rows of pages for each set i.e the navigation at the bottom of the gridview or the directional link

     thanks

    please see code below:

    /// <summary>

    ///

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void gvPositionManager_Sorting(object sender, GridViewSortEventArgs e)

    {

    string sortExpression = e.SortExpression;if (GridViewSortDirection == SortDirection.Ascending)

    {

    GridViewSortDirection = SortDirection.Descending;

    SortGridView(sortExpression, "DESCENDING");

    }

    else

    {

    GridViewSortDirection =
    SortDirection.Ascending;SortGridView(sortExpression, "ASCENDING");

    }

    }

    /// <summary>

    ///

    /// </summary>

    /// <param name="sortExpression"></param>

    /// <param name="direction"></param>

    private void SortGridView(string sortExpression, string direction)

    {

    //DataTable dt = GetData().Tables[0];

    DataSet ds = (DataSet) Cache["dsResult"];

    dt = ds.Tables[0];

     

    DataView dv = new DataView(dt);

    dv.Sort = sortExpression + direction;

    gvPositionManager.DataSource = dv;

    gvPositionManager.DataBind();

    }

    /// <summary>

    ///

    /// </summary>

    /// <param name="sender"></param>

    /// <param name="e"></param>

    protected void gvPositionManager_PageIndexChanging(object sender, GridViewPageEventArgs e)

    {

    gvPositionManager.PageIndex = e.NewPageIndex;

    gvPositionManager.DataBind();

    }

    This above all: to thine own self be true.

    William shakespeare, Hamlet
  • Re: C# Using Linq to Query DataTable and Bind to Gridview

    05-16-2008, 6:07 PM

    Hi Kipo,

    I am wondering if you could help me with this...I am quire new to linq and i am trying to construct a dynamic where clause

    for my linq query now i have been looking all over the web for examples but i cant find anything that seem to work for me...

    here is my query and i want my where clause to be composed of the following dynamic string returned by the method

    CreateFilter():

    this method builds up my query based on whether a user selected a series of drop down boxes and input data into text boxes or not .i.e it it does an AND or OR depending on what is selected or not selected

    I have the btnViewReport_Click(object sender, EventArgs e) Method which executes the query and puts the result in my gridview please find both methods below

    while the CreateFilter Method should build up the where clause but i cant get it to work, I read about using the Lambda expression but i dont know how to do this after looking at so many articles on the web they all seem to be in VB.Net and/or complicated predicates on how to do this which i still tried to no avail, please help!! i have marked out the problem area

    //see my Where Clause

    TestData = createFilter();

    /****************************************************************************************************

    Get All Data stored in the Cache which is the whole ResultSet returned By uspSearchPositionManager

    all 10512 rows and 103 columns into a DataTable "dt" via DataSet "ds"

    ****************************************************************************************************/

    dt = dsCache.Tables[0];

    /*LINQ query Expression: This Linq query object returns a filtered resultset data From the dataTable "dt"

    * Based on User input and selection Criteria on the webPage

    */

    /****************************************************************************************/

    string[] words = createFilter().Split(new string[] { "\r\n" }, StringSplitOptions.None);

    var queryWhere = dt.AsEnumerable();

    foreach (string word in words)

    {

    String thisWord = word;

    queryWhere = queryWhere.Where(Func<string>(word)(word.Contains(thisWord))); //this did not work!!!!! 6hours trying!!

    }

    /****************************************************************************************/

    IEnumerable<DataRow> query =

    from c in dt.AsEnumerable()

    //******************Different where clauses i was tring to use to make it work!!******************************************/

    //where c = createFilter()

    //where c.Field<string>("SecurityCode") == createFilter()

    //where c.Field<string>("SecurityCode") == createFilter()

    where c = createFilter().Split("\r\n")

    /****************************************************************************************/

    where c = createFilter() ///This Does not work!!!!!!!!!!!!!!!!!!!!

    select c;

    //see my Where Clause to know the format in the immediate window

    TestData = createFilter();

    /*Create a new DataTable "dtFormat" which then holds the filtered data returned by the LINQ query

    * formated into a DataTable to holding prior whihc is then bound to the gridview to return the

    * filtered data

    */

    dtFormat = new DataTable();

    if (dtFormat.Rows.Count != 0)
    {
    dtFormat = query.CopyToDataTable<DataRow>();
    }
    dataKeys =
    new string[1] { "SecurityCode" };

    gvPositionManager.DataKeyNames = dataKeys;

    gvPositionManager.DataSource = dtFormat;

    gvPositionManager.DataBind();

    //if Gridview has no rows then display the message

    if (gvPositionManager.Rows.Count == 0)

    {

    lblOutput.Visible =
    true;lblOutput.Text = "there are no records returned for the search criteria";

    }

    }

    /// <summary>

    /// This Method builds the where Clause the LINQ Query

    /// based on User selected criteria

    /// </summary>

    /// <returns></returns>

    private string createFilter()

    {

    StringBuilder filter = new StringBuilder();

    string ValueDate = msddlValueDate.List.SelectedValue;

    if (!ValueDate.Equals("-- Select All --"))

    {

    //filter.Append("ValueDate == msddlValueDate.List.SelectedItem.ToString() && \r\n ");

    filter.Append("c.Field<string>(" + "ValueDate" + ") == msddlValueDate.List.SelectedItem.ToString() && \r\n ");

    //filter.Append(c.Field<string>(" + ValueDate + ") == msddlValueDate.List.SelectedItem.ToString() && \r\n ");

    }

    if (msddlSecurity.Text.Equals(""))

    {

    // filter.Append("SecurityCode == @SecurityCode && \r\n ");

    filter.Append("c.Field<string>(" + "SecurityCode" + ") == msddlSecurity.Text && \r\n ");

    }

    string Currency = msddlCurrency.List.SelectedValue;

    if (!Currency.Equals("-- Select All --"))

    {

    //filter.Append("Currency == msddlCurrency.List.SelectedItem.ToString() && \r\n ");

    filter.Append("c.Field<string>("+ "Currency" + ") == msddlCurrency.List.SelectedItem.ToString() && \r\n ");

    }

    string Product = msddlProduct.List.SelectedValue;

    if (!Product.Equals("-- Select All --"))

    {

    //filter.Append("Product == msddlProduct.List.SelectedItem.ToString() && \r\n ");

    filter.Append("c.Field<string>(" + "Product" + ") == msddlProduct.List.SelectedItem.ToString() && \r\n ");

    }

    string CountryIssue = msddlCountry.List.SelectedValue;

    if (!CountryIssue.Equals("-- Select All --"))

    {

    //filter.Append("CountryIssue == msddlCountry.List.SelectedItem.ToString() && \r\n ");

    filter.Append("c.Field<string>(" + "CountryIssue" + ") == msddlCountryIssue.List.SelectedItem.ToString() && \r\n ");

    }

    if (txtValueFrom.Text.Equals(""))

    {

    //filter.Append("txtValueFrom == txtValueFrom.Text && \r\n ");

    filter.Append("c.Field<string>(" + "SettledValue" +") == txtValueFrom.Text && \r\n ");

    }

    if (txtValueTo.Text.Equals(""))

    {

    //filter.Append("txtValueTo == txtValueTo.Text && \r\n ");

    filter.Append("c.Field<string>(" + "SettledValue" + ") == txtValueTo.Text && \r\n ");

    }

    string Location = msddlLocation.List.SelectedValue;

    if (!Location.Equals("-- Select All --"))

    {

    //filter.Append("Location == msddlLocation.List.SelectedItem.ToString() && \r\n ");

    filter.Append("c.Field<string>(" + "Location" + ") == msddlLocation.List.SelectedItem.ToString() && \r\n ");

    }

    /********* Not included as there seems to be no column for this value**********

    string LongShort = msddlLongShort.List.SelectedValue;

    if (!LongShort.Equals("-- Select All --"))

    {

    //filter.Append("LongShort == msddlLongShort.List.SelectedItem.ToString() && \r\n ");

    filter.Append("c.Field<string>(" + "LongShort" + ") == msddlLongShort.List.SelectedItem.ToString() && \r\n ");

    }

    //*********************************************************************************/

    string Tag = msddlTag.List.SelectedValue;

    if (!Tag.Equals("-- Select All --"))

    {

    //filter.Append("Tag == msddlTag.List.SelectedItem.ToString() && \r\n ");

    filter.Append("c.Field<string>(" + "Tag" + ") == msddlTag.List.SelectedItem.ToString() && \r\n ");

    }

    /* */ return filter.ToString();

    }

    This above all: to thine own self be true.

    William shakespeare, Hamlet
  • Re: C# Using Linq to Query DataTable and Bind to Gridview

    05-17-2008, 4:24 AM
    • Loading...
    • kipo
    • Joined on 07-20-2006, 7:10 AM
    • Croatia
    • Posts 1,469

    Here is an example how you could solve your problem (it's LINQ 2 SQL, but I hope you'll get the general idea):

            NorthWindDataContext db = new NorthWindDataContext();
            var customers = from p in db.Customers
                            select p;
            if (DropDownList1.SelectedIndex > 0)
            {
                customers = customers.Where(o => o.CompanyName == DropDownList1.SelectedValue);
            }
            if (DropDownList2.SelectedIndex > 0)
            {
                customers = customers.Where(o => o.Country == DropDownList2.SelectedValue);
            }
            if (DropDownList3.SelectedIndex > 0)
            {
                customers = customers.Where(o => o.ContactTitle == DropDownList3.SelectedValue);
            }
            GridView1.DataSource = customers;
            GridView1.DataBind();

  • Re: C# Using Linq to Query DataTable and Bind to Gridview

    05-17-2008, 6:46 AM

    Hi Kipo,

    Thanks for your speedy reply i really appreciate it, and i have seen an example like this before, but theonly thing is that i am using LINQ rather than linQ to SQL, hence my table is not

    coming from a DataBase directly as i am now querying a DataTable, so how do i then construnct the Linq query?

    can i do something like this code block:

    /////////////////////////////////////////////////////Start//////////////////////////////////////////////////////////

    var query = from c in dt.AsEnumerable()

    select c;

    Then write my if statement to determine what my where clause would be i.e