I did something similar for web application I made. You can utilize the OnSelecting event of asp:SqlDatasource (I would recommend to use this instead of dynamically building the select command in the codebehind) for dynamically adjusting the parameters of the select command.
I am not sure if this is the optimal way of doing this but it works.
My markup looked like this (GridView tag simplified):
<asp:SqlDataSource ID="SelectItemsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:hubConnectionString %>"
ProviderName="<%$ ConnectionStrings:hubConnectionString.ProviderName %>"
SelectCommand="SELECT itemEntity.id, itemEntity.name, itemEntity.filename, itemEntity.type, itemEntity.added, userEntity.name FROM item AS itemEntity
LEFT OUTER JOIN USER AS userEntity ON itemEntity.uploader = userEntity.id WHERE itemEntity.type like @type ORDER BY itemEntity.added DESC"
OnSelecting="onItemSelecting">
<SelectParameters>
<asp:Parameter Name="@type" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:GridView ID="ItemGrid" runat="server" DataSourceID="SelectItemsDataSource"/> // Simplified
Notice the OnSelecting attribute.
Then in the codebehind you can simply handle the OnSelecting event:
protected void onItemSelecting(object sender, SqlDataSourceSelectingEventArgs e)
{
// Type value NOT given and parameter exists - Set wildcard
if (Request.QueryString["type"] == null && e.Command.Parameters.Contains("@type"))
{
e.Command.Parameters["@type"].Value = "%";
return;
}
if (Request.QueryString["type"] != null && e.Command.Parameters.Contains("@type"))
e.Command.Parameters["@type"].Value = Request.QueryString["type"];
}
I believe the Command.Parameters methods are sql injection safe. If not then someone please correct me.