title: ASP.NET LinqDataSource WHERE clause
body: <p>I need to make a WHERE clause for my <code>LinqDataSource</code> which depends on the currently logged in user. Of course, I have access to the currently logged in user in the code-behind and I specifically need the user ID to fetch only data belonging to him/her from the database.</p>
  
  <p>It works fine when I add the <code>Where</code> attribute to the <code>&lt;asp:LinqDataSource /&gt;</code> tag but since server controls cannot have <code>&lt;% %&gt;</code> tags in them, I tried to set the <code>Where</code> attribute in the code-behind, in <code>OnLoad</code>, before data-binding the GridView which is connected to my data source.</p>
  
  <p>However, when setting the attribute in the code-behind, it seems to have no effect. It works fine when I specify it manually (and statically) in the <code>ascx</code> code, but not from the code-behind.</p>
  
  <p>I'm guessing I'm doing things in the wrong order or at the wrong times. How do I do this?</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Came up with this hack. I use a dummy label <code>lblViewedUserID</code> with <code>Visible="false"</code> to get a control from which I can extract the user ID. I set the text of this label from the code-behind before databinding.</p>
  
  <p>I also added <code>&lt;WhereParameters&gt;</code> with a <code>&lt;asp:ControlParameter /&gt;</code> with a bunch of attributes.</p>
  
  <pre><code>&lt;asp:LinqDataSource ID="dsLinqSource" AutoPage="true" AutoSort="true"
    ContextTypeName="Ortrac.Common.Dbml.OrComDataContext"
    EnableDelete="false" TableName="myTableName" EnableInsert="false"
    EnableUpdate="false" runat="server" Select="new(Edited, Activity)"
    Where="TheUserID.ToString().Equals(@ViewedUserID)"&gt;&lt;%-- HACK! --%&gt;
    &lt;WhereParameters&gt;
      &lt;asp:ControlParameter Name="ViewedUserID" ControlID="lblViewedUserID"
                            Type="String" PropertyName="Text" /&gt;
    &lt;/WhereParameters&gt;
  &lt;/asp:LinqDataSource&gt;
  
  &lt;%-- Dummy label --%&gt;
  &lt;asp:Label runat="server" ID="lblViewedUserID" Visible="false" /&gt;
  </code></pre>
  
  <p>Is this really how you program ASP.NET?</p>