ASP.NET Gridview that shows all records if dropdown filter is not selected

Posted by admin on April 3, 2009 under 4-Code snippets |

If you have a grdiview that is tied to a dropdown selector box, it will not show any records when the page loads and the dropdown defaults to a “Select” state. Here is one simple way to have the gridview show all records in this case:

<asp:DropDownList ID=”ddlCustomers” runat=”server”

            AutoPostBack=”True” DataSourceID=”ds_ddlCustomers” AppendDataBoundItems=”true”

            DataTextField=”CustName” DataValueField=”CustID”>

            <asp:ListItem Text=”All” Value=”0″></asp:ListItem>

          </asp:DropDownList>

 

Gridview datasource Select:

                SelectCommand=”SELECT CustID, CustName, CustPhone, CustEmail FROM tblCustomers WHERE (CustID = @CustID) OR (0 = @CustID) ORDER BY CustName”

 

<SelectParameters>

                  <asp:ControlParameter ControlID=”ddlCustomers” Name=”CustID”

                    PropertyName=”SelectedValue” Type=”Int32″ />

 </SelectParameters>

Explanation: In the dropdownlist declaration, I’ve added the AppendDataBoundItems=”true” attribute. I then add a list item that displays “All” with a value of 0. In the datasource for the gridview, the SelectCommand has the additional OR clause 0 = @CustID. So when the page first loads, or when the user selects “All”, the dropdown has a value of 0, so 0=0 becomes true.

If you found my post helpful and it saved you time or money, please contribute by making a small donation. Even a dollar or two adds up!


Add A Comment