Sql – How to get the TotalRowCount from a LinqDataSource into a Literal

asp.netlinq-to-sql

I have a LinqDataSource that I use to calculate the number of rows in a table. I would like to update the value of literal with the number, with the following code, taken from MSDN (linqdatasourcestatuseventargs.totalrowcount.aspx):

protected void linqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
    Literal1.Text = e.TotalRowCount.ToString();
}

By how do I trigger the select event on the data source? The SqlDataSource class has a Select() method so that it can be triggered programmatically in e.g. Page_Load, but the LinqDataSource does not have this method. I currently solved the problem by binding my data source to an empty FormView element, but this is just too ugly.

I feel pretty confident that there is a much nicer way to get the total number of rows into my literal when using LinqToSql, I just don't know how to do so.

The suggestion by tvanfosson, of attaching an method to the data source's selected event, does unfortunately not solve my problem, because the select event is still not triggered when the page loads. (I have, by the way, already attached the _Selected method with the OnSelected attribute, like this)

<asp:LinqDataSource ID="linqDataSource1" runat="server"
    OnSelected="linqDataSource1_Selected">

Best Answer

Hook up your method as an event handler for the Selected event in Page_Load.

public void Page_Load( object sender, EventArgs e )
{
     linqDataSource1.Selected += LinqDataSource1_Selected;
}

protected void LinqDataSource1_Selected(object sender, LinqDataSourceStatusEventArgs e)
{
    Literal1.Text = e.TotalRowCount.ToString();
}
Related Topic