Passing textbox in gridview header template as a parameter in a sqldatasource select
<p>I have a gridview that displays the contents of a database table, using an sqlDataSource. That part (including inserting, updating and deleting rows) works perfectly.  What I am wanting to do is add a "search" function to restrict the rows returned to a user entered name.  I have a textbox for the name to be searched and a "Search" button in the headertemplate as such:</p>

<pre><code> &lt;HeaderTemplate&gt;
    &lt;asp:Button ID="btnShowAll" runat="server" CausesValidation="False" CommandName="ShowAll" Text="Show All" Visible="false" /&gt;
    &lt;asp:Button ID="btnSearch" runat="server" CausesValidation="True" CommandName="Search" Text="Search" ValidationGroup="vldSearch" /&gt;
    &lt;asp:TextBox ID="txtSearchName" runat="server"&gt;&lt;/asp:TextBox&gt;
    &lt;asp:RequiredFieldValidator ID="vldSearchName" runat="server" ErrorMessage="You have to provide an attorney name to search for." Text="*" ControlToValidate="txtSearchName" ValidationGroup="vldSearch" ForeColor="White"&gt;&lt;/asp:RequiredFieldValidator&gt;
 &lt;/HeaderTemplate&gt;   
</code></pre>

<p>Now, in the RowCommand event handler, I have the following code:</p>

<pre><code> Case "Search"
   If Page.IsValid Then
       Dim btnSearch As Button = Me.dgAttorneys.HeaderRow.FindControl("btnSearch")
       Dim btnShowAll As Button = Me.dgAttorneys.HeaderRow.FindControl("btnShowAll")
       Dim txtSearchName As TextBox = Me.dgAttorneys.HeaderRow.FindControl("txtSearchName")
       Me.sqlAttorneys.SelectCommand = "SELECT [userID], [login], [username], [password] FROM [attorney] WHERE [username] LIKE '%' + @username + '%' ORDER BY [login]"
       Dim parmUserName As New ControlParameter("username", "txtSearchName", "Text")
       Me.sqlAttorneys.SelectParameters.Add(parmUserName)
       Me.dgAttorneys.DataBind()
       Me.dgAttorneys.PageIndex = 0
       btnSearch.Visible = False
       btnShowAll.Visible = True
       txtSearchName.Visible = False
   End If
</code></pre>

<p>The DataBind fails, with the error:</p>

<p>Could not find control 'txtSearchName' in ControlParameter 'username'.</p>

<p>Any suggestions on alternative methods for achieving this?</p>

<p>Thanks.</p>
