ASP.NET Gridview filtering with Dropdowns - asp.net

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

Related

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();

Getting "ORA-01036: illegal variable name/number" in DeleteCommand of SqlDataSource

I have a GridView. It's connected to a SqlDataSource. My database is Oracle.
When I run the webpage, SELECT command works and I see the items in the list. When I click Delete button, I get this error:
ORA-01036: illegal variable name/number
Here is my GridView and SqlDataSource:
<telerik:RadAjaxPanel ID="ajaxMyLinks" runat="server" width="100%" LoadingPanelID="RadAjaxLoadingPanel1">
<telerik:RadGrid ID="gridMyLinks" runat="server" DataSourceID="SqlDataSourceMyLinks" AllowAutomaticDeletes="True" AllowPaging="True" BackColor="White" BorderColor="White" PageSize="5" ShowHeader="False">
<MasterTableView AutoGenerateColumns="False" DataSourceID="SqlDataSourceMyLinks" DataKeyNames="N_USER_LINK_ID">
<Columns>
<telerik:GridHyperLinkColumn AllowSorting="False" DataNavigateUrlFields="V_LINK" DataNavigateUrlFormatString="{0}" DataTextField="V_LINK_TITLE" DataTextFormatString="{0}" FilterControlAltText="Filter column column" UniqueName="column" Target="_blank">
</telerik:GridHyperLinkColumn>
<telerik:GridButtonColumn ButtonType="ImageButton" CommandName="Delete" ImageUrl="Content/images/delete.png" UniqueName="column1">
</telerik:GridButtonColumn>
</Columns>
</MasterTableView>
<PagerStyle Mode="NextPrev" ShowPagerText="False" />
</telerik:RadGrid>
</telerik:RadAjaxPanel>
<asp:SqlDataSource ID="SqlDataSourceMyLinks" runat="server" ConnectionString="<%$ ConnectionStrings:DefaultConnection %>" SelectCommand="SELECT V_LINK_TITLE, V_LINK, N_USER_LINK_ID FROM TAPP_IFH_USER_LINK WHERE (N_USER_ID = :USER_ID) ORDER BY N_USER_LINK_ID DESC" DeleteCommand="DELETE FROM TAPP_IFH_USER_LINK WHERE (N_USER_LINK_ID = :USER_LINK_ID)" ProviderName="<%$ ConnectionStrings:DefaultConnection.ProviderName %>">
<DeleteParameters>
<asp:Parameter Name="USER_LINK_ID" Type="Int32"></asp:Parameter>
</DeleteParameters>
<SelectParameters>
<asp:SessionParameter Name="USER_ID" SessionField="USER_ID" />
</SelectParameters>
</asp:SqlDataSource>
Found the solution. Parameter names were not matching between column name in DB and parameter. Parameter name was USER_LINK_ID while column name was N_USER_LINK_ID.
If this is not the problem in your case, check this post out. It has more suggestions

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.

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.

Filter gridview

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>

Resources