views:

44

answers:

1

Hi all,

I have a ListView setup with LinqDataSource and a button that triggers search function. To avoid display data on page_load, I set ListView's DataSourceID in the Click event of the search button, bind it and set result data in LinqDataSource's Selecting event. It works as I expected but It does't look pretty to set DataSourceId in the button Click event every time the search button is clicked. How can I do this in a better and clearer way?

ASPX code:

<asp:LinqDataSource ID="LinqDataSource1" runat="server"
    ContextTypeName="WebApplication1.DataClasses1DataContext" EntityTypeName=""
    TableName="Persons" onselecting="LinqDataSource1_Selecting">
</asp:LinqDataSource>

<asp:ListView ID="ListView1" runat="server" >...</asp:ListView>

<asp:Button ID="Search" Text="Search" runat="server" Click="Search_Clicked"/>

ASPX.CS code:

protected void Search_Clicked(object sender, EventArgs e)
{
    ListView1.DataSourceID = LinqDataSource1.ID;
    ListView1.DataBind();
}

protected void LinqDataSource1_Selecting(object sender, LinqDataSourceSelectEventArgs e)
{
    //Search Criteria from CheckBoxList and TextBox applied here.
    DataClasses1DataContext data = new DataClasses1DataContext();
    var query = from result in data.Persons
                where result.ID > 2
                select result;
    e.Result = query;
}
A: 

I honestly don't see anything wrong with your approach, however, if you don't like it, an alternate approach would be to just statically set the DdataSourceID in your listview markup as usual, but set Visible="False", and only make it visible once the button has been clicked.

womp
Thanks for an answer, womp.I thought about it too but the problem doing that is when it binds, it still retrieves data from DB on page load without any search criteria. I just wondered if there's any way to bind datasource to listview and not retrieve data until specifically tell it to do so.
Kaz Yoshimura