Search code examples
asp.netlinq-to-sqllinqdatasource

How do I get values from a LinqDataSource?


I have an .aspx page with several LinqDataSources. A LinqDataSource is bound to a GridView and/or WebDataGrid based on other controls on the page. The grid may be filtered, as well, which may show fewer results.

The data sources are all bound dynamically to the grid (only one at a time). They rely on different contexts and tables. However, all the data sources have a column for email addresses. I would like to retrieve the email addresses from the grid, regardless of the LinqDataSource.

I'm absolutely lost. I've tried converting the LinqDS into various dataviews, datatables, lists, arrays, strings. This results in errors and null objects. I'm still trying to get my head around using reflection, but is that really necessary here? I've tried fiddling with the e.Result in the LinqDS Selected/Selecting events, but only end up with a DynamicClass1 object with no methods.

I would like to avoid having to make a specific query (manual) for each LinqDataSource. I'd rather convert the currently bound LinqDataSource to something usable (a table, an array, a list of strings, anything), so that I can access the values in the "Email" column (or even the first column, assuming "Email" is always the first column).

What are my options? Am I going about this all wrong? I'm still learning about Linq-to-SQL, and this is only a minor project so the option to move to Entity Framework or something else is on the table.

All I want to do is access these email addresses which are present in every LinqDataSource! I'm using VS2013 and ASP.NET 4.0.


Solution

  • There may be a better way, but you can use reflection in the "selected" event of the datasource. This assumes that the email address column is named "emailAddress".

    protected void LinqDataSource1_Selected(object sender, System.Web.UI.WebControls.LinqDataSourceStatusEventArgs e)
    {
        var results = (IEnumerable<object>) e.Result;
        var emailList = results.Select(ex => ex.GetType().GetProperty("emailAddress").GetValue(ex, null)).ToList();
    }