1
votes

So I have a .aspx page that is bound to some data. I can run a LINQ query and return it as an IQueryable object in the SelectMethod for the GridView control, and it will populate fine. What I am trying to do is populate the GridView based upon a selection from a ListBox control. Since the data is bound, I can't set the DataSource equal to the query. I could maybe figure out a way to re-use the SelectMethod based on a public string (which would in turn be based off the ListBox selection), but that would be pretty ugly.

Here is the gridview control on my .aspx page:

<asp:GridView runat="server" ID="employeesGrid"
    ItemType="Foo.Models.Employee" DataKeyNames="EmployeeID"
    SelectMethod="employeeGrid_GetData"
    AutoGenerateColumns="false">
    <Columns>
        <asp:DynamicField DataField="EmployeeID" />
        <asp:DynamicField DataField="FirstName" />
        <asp:DynamicField DataField="LastName" />
        <asp:DynamicField DataField="CompanyName" />
    </Columns>
</asp:GridView>

And here is my SelectMethod in the .cs:

    public IQueryable<Employee> employeeGrid_GetData()
    {
        FooContext db = new FooContext();
        var query = db.Employees.Where(e => e.CompanyName == "NameOfCompany");
        return query;
    }

That populates the GridView just fine on load, but it doesn't do much for me with updating on click.

And here is the button click method that I've tried but doesn't work. I get an error about not being able to use DataSource or DataSourceId when the GridView is bound to a data model:

    public void btn_RequestEmployees_Click(object sender, EventArgs e)
    {
        string currentlySelectedEmployer = lstbxEmployers.SelectedValue.ToString();
        FooContext db = new FooContext();
        var query = db.Employees.Where(employee => employee.CompanyName == currentlySelectedEmployer);
        employeesGrid.DataSource = query;
        DataBind();
    }

Any advice? Thanks.

1
Added the code I've tried. - Lapys

1 Answers

0
votes

Try it like this:

public IQueryable<Employee> employeeGrid_GetData()
    {
        string currentlySelectedEmployer = lstbxEmployers.SelectedValue.ToString();
        FooContext db = new FooContext();
        var query = db.Employees.Where(employee => employee.CompanyName == currentlySelectedEmployer);        
        return query;
    }