views:

668

answers:

2

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">
+1  A: 

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();
}
tvanfosson
A: 

I ended up dropping the data source and instead put the code in the code behind. Not really the point-and-click-programming that I was going for, but still quite short. I looks something like this:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        var context = new MyDataContext();

        numberOfModificationsLiteral.Text =
            (
                from modification in context.Modifications
                where modification.Start >= DateTime.Now
                select modification
            ).Count().ToString();
    }
}
Jan Aagaard