Filter gridview - asp.net

I have a gridview which I am binding through code behind, I want to filter the gridview based on the value given by the user in textbox.
It would be great if I'll be able to filter the gridview without any postback.
PLease help!
Thanks in advance

you could run a filter expression
<asp:sqldatasource id="articles" runat="server"
connectionstring="<%$ ConnectionStrings:aspa %>"
selectcommand="SELECT title, url, added, updated FROM aspx_articles ORDER BY title"
filterexpression="title LIKE '%{0}%' or url LIKE '%{0}%'">
<filterparameters>
<asp:controlparameter controlid="searchBox" propertyname="Text" />
</filterparameters>
</asp:sqldatasource>
or this way
Do you have a TextBox outside the GridView, and when you enter data into it and press a button, the GirdView should be filter on that data?
If so, make sure your select command can taka a parameter with the value you want to filter on. Add a ControlParameter to the SelectParameters colelction of the DataSource control (if you use a DataSource control).
Here is an example that uses the Northwind database, maybe this will help you:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
DataKeyNames="ProductID" DataSourceID="SqlDataSource1" ShowFooter="True">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False"
ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [UnitsInStock], [UnitPrice] FROM [Alphabetical list of products] WHERE ([ProductName] LIKE '%' + #ProductName + '%')">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox1" DefaultValue="%" Name="ProductName" PropertyName="Text"
Type="String" />
</SelectParameters>
</asp:SqlDataSource>
codes found here http://forums.asp.net/p/1034014/2904713.aspx

If you're using paging, I would recommend using something else (like the Microsoft Ajax Library's dataView). Because gridview paging and client-side filtering wouldn't mesh too well. But if you're not doing paging, you could do something similar to this or this.

The grid view is made for manipulation during post back. If you were to do this entirely on the client side, you'd use a JavaScript suite that would work on any table, not confined to the grid view. If it were me, I would simply use AJAX by wrapping the grid view and text box in an Update Panel. To the end user, the behavior is the same.
EDIT to include Sample code:
<asp:ScriptManager ID="ScriptManager1" AllowCustomErrorsRedirect="false" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:TextBox runat="server" ID="txtFilterString" ></asp:TextBox>
<asp:Button runat="server" ID="btnFilter" Text="FilterResults" onclick="btnFilter_Click" />
<asp:GridView runat="server" ID="grdResults"
DataKeyNames="Id"
AllowSorting="true" AllowPaging="true" PageSize="20"
PagerSettings-Mode="NumericFirstLast">
<Columns>
.....
</Columns>
</asp:GridView>
</asp:UpdatePanel>

Related

ASP.NET Gridview filtering with Dropdowns

I have a Gridview which uses a dropdown list to provide a value applied to a SQL query which filters to the applicable data. The issue is that when an item is selected from the list the gridview does not update, the DefaultValue remains as the filter.
I've tried a number of alternatives seen though StackOverflow like by directly binding the value in the markup but to no success yet.
<label for="City" class="control-label">Filter by City:</label>
<div>
<asp:DropDownList ID="CityDropdown" runat="server" Width="123px" >
<asp:ListItem>Aberdeen</asp:ListItem>
<asp:ListItem>Armagh</asp:ListItem>
<asp:ListItem>Bangor</asp:ListItem>
<asp:ListItem>Bath</asp:ListItem>
</asp:DropDownList>
</div>
</div>
<hr />
<asp:Panel ID="PanelFoodbanks" runat="server">
<asp:GridView ID="ListFoodbanks" runat="server" AutoGenerateColumns="False" AllowSorting="True" DataSourceID="SqlDataSource_FindCity" EmptyDataText="There are no data records to display." CssClass="table table-responsive" GridLines="None">
<Columns>
<asp:BoundField DataField="Id" SortExpression="Id" ItemStyle-CssClass="hidden" HeaderStyle-CssClass="hidden">
<HeaderStyle CssClass="hidden" />
<ItemStyle CssClass="hidden" />
</asp:BoundField>
<asp:BoundField DataField="Other Field" HeaderText="OF" SortExpression="Other Field" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource_FindFoodbanks" runat="server" ConnectionString="<%$ ConnectionStrings:dbcon %>" SelectCommand="SELECT * FROM [Table] WHERE ([City] = #CityDropdown)">
<SelectParameters>
<asp:Parameter Name="CityDropdown" DefaultValue="Aberdeen"/>
</SelectParameters>
</asp:SqlDataSource>
Preferably the gridview just update dynamically when a different value in the dropdown is selected, rather than having the need to press another button etc.
Thanks in advance for any help or pointers.
I believe you need to use ControlParameter bound to city dropdown list control in your SQL Datasource:
<asp:SqlDataSource ID="SqlDataSource_FindFoodbanks" runat="server" ConnectionString="<%$ ConnectionStrings:dbcon %>" SelectCommand="SELECT * FROM [Table] WHERE ([City] = #CityDropdown)">
<SelectParameters>
<asp:ControlParameter ControlID="CityDropdown" Name="CityDropdown"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
Also add AutoPostBack="true" ondropdown list
<asp:DropDownList ID="CityDropdown" AutoPostBack="true" runat="server" Width="123px" >
Note: I noticed that in your code GridView is using DataSourceID SqlDataSource_FindCity and not SqlDataSource_FindFoodbanks

GridView and SqlDataSoruce SORTING issue

I have got very basic Product data table, I set up my grid view data source to sqlDataSoruce with paging and sorting options true.
But I also have a DropDownList and if a user chooses a certain product group ( Vegetables, Fruits, Frozen etc), grid view only shows that product group items.
String sqlSearchByProduct = " SELECT ID, pID,pGroupID, pName, pPrice, Status, Stock FROM productsTable WHERE (pGroupID= ProductGroupIDDropDownList.SelectedItem.Value)";
sqlDataSource.SelectCommand = sqlSearchByProduct ;
The grid shows all products from groupID selected from dropdownlist but the issue is when I want to sort it by name or price, grid view shows all products again.
I will be very grateful if you know how to fix this issue.
Thank you.
You need to keep SelectedValue of the dropdown and the easiest way to do so is to bind all data declaratively. Something like this:
<asp:DropDownList ID="ddCategory" runat="server" DataTextField="categoryname"
DataValueField="categoryid"
AppendDataBoundItems="true" DataSourceID="sqlCategory" AutoPostBack="true">
<asp:ListItem Value="0" Text="- Select -"></asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="sqlCategory" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindCnn %>"
SelectCommand="select categoryid,categoryname from dbo.categories">
</asp:SqlDataSource>
<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="False" AllowPaging="True" PageSize="5" DataKeyNames="ProductID" DataSourceID="sqlNWind">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ProductID" InsertVisible="False" ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqlNWind" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindCnn %>"
SelectCommand="SELECT Products.ProductID, Products.ProductName FROM Products where (#categoryid=0 or CategoryID=#categoryId)">
<SelectParameters>
<asp:ControlParameter Name="categoryid" ControlID="ddCategory" Type="Int32" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
No code behind required.
Side note: never build sql query string like this
" ... WHERE (pGroupID= ProductGroupIDDropDownList.SelectedItem.Value)"
Such code is prone to SQL Injection attack. Always use parameters.
Have you rebound your data to the gridview, e.g. below
GridView1.DataBind();

ASP.net How to use dropdownlist for retriving data from database

I have a button,dropdownlist,and gridview. and i want that when i select any option from dropdownlist and click button . then the releted data is show into gridview .i have a problem that the data show in gridview but gridview d'nt work with the button
my code is
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
DataSourceID="SqlDataSource1" DataTextField="E_NAME" DataValueField="E_ID">
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [E_ID], [E_NAME] FROM [EMP_DETAIL]">
</asp:SqlDataSource>
<br />
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [E_ID], [E_NAME], [E_CITY], [E_AGE], [E_DEPARTMENT] FROM [EMP_DETAIL] WHERE ([E_ID] = #E_ID)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="E_ID"
PropertyName="SelectedValue" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="E_ID" DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="E_ID" HeaderText="E_ID" ReadOnly="True"
SortExpression="E_ID" />
<asp:BoundField DataField="E_NAME" HeaderText="E_NAME"
SortExpression="E_NAME" />
<asp:BoundField DataField="E_CITY" HeaderText="E_CITY"
SortExpression="E_CITY" />
<asp:BoundField DataField="E_AGE" HeaderText="E_AGE" SortExpression="E_AGE" />
<asp:BoundField DataField="E_DEPARTMENT" HeaderText="E_DEPARTMENT"
SortExpression="E_DEPARTMENT" />
</Columns>
</asp:GridView>
</form>
Set the AutoPostBack property of Drop-down to False or remove it:-
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="E_NAME" DataValueField="E_ID">
</asp:DropDownList>
Since, you need the results on button click, the form will be refreshed after button click and taking the selected value in drop-down.

asp SqlDataSource Filter Expression; multiple Search Boxes

I am trying to perform a single search on a single column of data in an asp:GridView, however I want multiple filter (search) boxes above each column so one could search within its own perspective column. What would clearly fix this theoretically is to have multiple FilterExpressions. I am using VB and am very new and easily misunderstood with VB, please bare with:
PS. I have gotten it to work no problem when only having ONE filter (search) box, this currently doesn't do anything
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="xxx"
ProviderName="xxxx"
SelectCommand="SELECT [ddiID], [volusionID], [Customer], [email], [Total], [SumOfTotal] FROM [BBnewsalesQry] ORDER BY [Customer]"
FilterExpression="customer like '%{0}%' OR ddiID like '%{0}%'">
<FilterParameters>
<asp:ControlParameter Name="ddiID" ControlID="ddiIDSearch" PropertyName="Text" />
<asp:ControlParameter Name="customer" ControlID="txtSearch" PropertyName="Text" />
</FilterParameters>
</asp:SqlDataSource>
<div>
<b>DDI Search:</b> <asp:TextBox ID="ddiIDSearch" runat="server" />
<b>Customer Search:</b> <asp:TextBox ID="txtSearch" runat="server" />
<asp:ImageButton ID="btnSearch" ImageUrl="http:xxx" runat="server" />
<asp:ImageButton ID="btnClear" ImageUrl="http:xxx" runat="server" />
</div>
Then inside the GridView:
<asp:TemplateField HeaderText="ddiID" SortExpression="ddiID">
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lblddiid" Text='<%#HighlightText(Eval("ddiid")) %>'
CssClass="TextField" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="volusionID" HeaderText="volusionID" ReadOnly="True" SortExpression="volusionID" />
<asp:TemplateField HeaderText="customer" SortExpression="customer">
<ItemStyle HorizontalAlign="Left" />
<ItemTemplate>
<asp:Label ID="lblcustomer" Text='<%#HighlightText(Eval("customer")) %>'
CssClass="TextField" runat="server" />
</ItemTemplate>
</asp:TemplateField>
you are referencing the same parameter twice - try the following:
FilterExpression="customer like '%{0}%' OR ddiID like '%{1}%'"
I have resolved the problem of create two or more "Like clause" in the "Where" statement using:
Where CHARINDEX(#Par1, Col1)<>0) and ...

Link to records with a specific letter in a GridView

I have an ASP.NET GridView in a Web Form. This GridView using a SqlDataSource and utilizes paging and searching. For the sake of reference, here is the trimmed down version of it:
<asp:SqlDataSource ID="myDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:DB %>"
SelectCommand="SELECT p.[ID], p.[Name], p.[Email], l.[State], l.[City] FROM [Person] p, [Location] l WHERE p.[LocationID]=l.[ID] ORDER BY p.[Name]"
UpdateCommand="UPDATE [Person] SET [Email] = #Email WHERE [ID] = #ID"
/>
<asp:GridView ID="myGridView" runat="server" DataSourceID="myDataSource"
AllowPaging="true" AllowSorting="true" PageSize="25" AutoGenerateEditButton="true"
DataKeyNames="ID">
<Columns>
<asp:BoundField DataField="ID" Visible="false" />
<asp:TemplateField HeaderText="Person" SortExpression="Name">
<ItemTemplate>
<asp:Literal ID="nameLit" runat="server" Text='<%# Bind("Name") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Email" SortExpression="Email" HeaderText="Email Address" />
<asp:TemplateField HeaderText="Location" SortExpression="City">
<ItemTemplate>
<asp:Literal ID="cityLit" runat="server" Text='<%# Bind("City") %>' />
<asp:Literal ID="stateLit" runat="server" Text='<%# Bind("State") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The data source has a lot of records. At least 25,000. Because of this, I want to allow the user to filter by state. I want to provide a drop down list with a list of states. When a user changes the drop down list, the results in the grid view will be filtered by the selected state. However, I do not know how to do this with a SqlDataSource. Can someone please explain to me how to accomplish this?
Thank you!
First of all, let's add the DropDownList, and a SqlDataSource to populate it:
<asp:dropdownlist runat="server" id="StateDropDownList" DataSourceId="StateDataSource" DataTextField="State" DataValueField="State" />
<asp:sqldatasource runat="server" ConnectionString="<%$ ConnectionStrings:DB %>" SelectCommand="SELECT DISTINCT State FROM Location" />
Then we change your existing data source to use a State parameter and read the parameter's value from the DropDownList:
<asp:SqlDataSource ID="myDataSource" runat="server" ConnectionString="<%$ ConnectionStrings:DB %>"
SelectCommand="SELECT p.[ID], p.[Name], p.[Email], l.[State], l.[City] FROM
[Person] p INNER JOIN [Location] l ON p.[LocationID]=l.[ID]
WHERE (l.State = #State) ORDER BY p.[Name]"
UpdateCommand="UPDATE [Person] SET [Email] = #Email WHERE [ID] = #ID"
<SelectParameters>
<asp:ControlParameter ControlID="StateDropDownList" Name="State"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
/>
That should be all you need.
BTW, top tip: I changed your query slightly to use INNER JOIN syntax rather than doing the table join in a WHERE clause. There's some great info here on INNER JOIN.
Top tip #2: Paging in the GridView is a bit naive - every time you change pages, the GridView is reading all 25 000 records in your table, then throwing away the ones it doesn't need. There's a great article here (and plenty of questions on SO!) on doing custom paging with a Gridview.

Resources