Ok, so full example using SqlDataSource (as Kendrick mentioned):
First you need to collect the parameters from your query, which it looks like you are already doing in a textbox somewhere. Something like this:
<asp:Label ID="lblLastName" runat="server" AssociatedControlID="tbLastName" Text="Last Name" ClientIDMode="Static" /> <asp:TextBox ID="tbLastName" runat="server" ClientIDMode="Static" /> <asp:Button ID="btnSearch" runat="server" ClientIDMode="Static" Text="Search" />
Now we need to take your Raw Inline SQL out of the code behind and move it into a SqlDataSource. We also want to get rid of the potential SQL Injection you have in your query by using a parameterized query instead :) In order to do that we need to hook up our TextBox to the parameter, but luckily DataSource controls allow us to do this without any code by using SelectParameters.
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ContactManagerConnectionString %>" SelectCommand="SELECT LastName + ', ' + FirstName + ' ' + MiddleInitial AS 'Name', UserName AS 'User Name', StreetAddress FROM CustomersMaster WHERE (LastName LIKE '%' + @SearchText + '%')"> <SelectParameters> <asp:ControlParameter ControlID="tbLastName" ConvertEmptyStringToNull="true" Name="SearchText" PropertyName="Text" DbType="String" /> </SelectParameters> </asp:SqlDataSource>
Once those two pieces are in place it is just a matter of setting up your grid the way you want, and setting the AllowPaging property to true.
<asp:GridView runat="server" AllowPaging="True" DataSourceID="SqlDataSource1" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="Name" HeaderText="Name" ReadOnly="True" SortExpression="Name" /> <asp:BoundField DataField="User Name" HeaderText="User Name" SortExpression="User Name" /> <asp:BoundField DataField="StreetAddress" HeaderText="StreetAddress" SortExpression="StreetAddress" /> </Columns> </asp:GridView>
VOILA!
Codeless paging*
* It is worth noting that this is pretty poor in terms of optimization as all the paging work is done on the Web Server. To really make this efficient you would want to employ some paging at the database level. Otherwise you will bring back every record every single time.
Where LastName Like '%"+ SearchText.Text.Trim() + "%'";because the user could enter, for example,'; DELETE FROM CustomersMaster;--in the SearchText text box, click the query button, and your CustomersMaster table would be erased