How to handle empty return from database with gridview?
I have a gridview that is bound to an ObjectDataSource, which retrieves records from a database to display in the gridview. The procedure for returning the records takes in a search string and displays the relevant results. However when there are no results from the database, I get an empty gridview with the page numbers along the bottom, as if it returned all the records from the database, as shown in the pic below:
I have set both the EmptyDataText and EmptyDataTemplate properties, but they do not show when there are no results.
Anyone know what's going on here?
Here's the asp for the ObjectDataSource and GridView:
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" EnablePaging="True" SelectCountMethod="GetUsersCount"
SelectMethod="GetUsers" SortParameterName="sortColumn" TypeName="WebsiteBuilder.Core.UUser"
OnSelecting="ObjectDataSource1_Selecting">
<SelectParameters>
<asp:Parameter Name="searchExpression" Type="String" DefaultValue="" />
</SelectParameters>
</asp:ObjectDataSource>
<asp:GridView ID="grdUsers" runat="server" CssClass="grdUsers" AutoGenerateColumns="false"
OnDataBound="grdUsers_DataBound" DataSourceID="ObjectDataSource1" AllowPaging="true"
AllowSorting="true" OnRowCommand="grdUsers_RowCommand" PageSize="5" EmptyDataText="No Results">
<PagerSettings FirstPageText="First" LastPageText="Last" Mode="NumericFirstLast"
PageButtonCount="5" Position="Bottom" />
<PagerStyle CssClass="pagination" HorizontalAlign="Center" VerticalAl开发者_开发问答ign="Middle" />
<EmptyDataTemplate>No Results</EmptyDataTemplate>`
Here is the code for the selecting event:
protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
if (!String.IsNullOrEmpty(this.txtSearchBox.Text))
{
e.InputParameters["searchExpression"] = "%" + this.txtSearchBox.Text + "%";
}
else return;
}
And the code for fetching the data:
cmd.AddParameter("searchExpression", searchExpression);
cmd.AddParameter("sortExpression", sortColumn);
cmd.AddParameter("startRowIndex", startRowIndex);
cmd.AddParameter("maximumRows", maximumRows);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
DataTable dt = ds.Tables[0];
int i = dt.Rows.Count;
return ds.Tables[0];
When I check i in debug the value is 0. My question is why the gridview is not showing the EmptyDataTemplate and why it is still showing multiple page numbers when there are no rows.
I would just bind the empty result set to the GridView, and then use the OnDataBound event to perform the appropriate logic, i.e. hide the GridView, display a "No Results" label, etc.
personally if the datasource is null or empty, I would not even bind it to the grid.
精彩评论