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();
Related
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
I have a Visual Studio 2010 asp.net page in VB where I have joined multiple tables with the SqlDataSource to display specific columns in a gridview. After the table join, I have a dropdownlist where I want it to display only those rows whose "SKillGroup" column value is equivalent to the selected item on the dropdownlist. However when running the page, the dropdownlist only has one selected item (the item being Hardware) which is duplicated in the list.
My problem is how do I make it so that the dropdownlist shows all three items of 'Hardware' 'Software' and 'Network' and depending on the selected search populate it into the gridview?
Here is my code for dropdownlist and gridview
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
DataSourceID="ProblemDataSource" DataTextField="SkillGroup"
DataValueField="SkillGroup">
<asp:ListItem Selected="True">Hardware</asp:ListItem>
<asp:ListItem Selected="True">Software</asp:ListItem>
<asp:ListItem Selected="True">Network</asp:ListItem>
</asp:DropDownList>
<asp:GridView ID="ProblemGridView" runat="server" AutoGenerateColumns="False"
DataSourceID="ProblemDataSource" style="margin-top: 0px"
AllowPaging="True">
<Columns>
<asp:BoundField DataField="ProblemID" HeaderText="ProblemID"
SortExpression="ProblemID" />
<asp:BoundField DataField="CustomerID" HeaderText="CustomerID"
SortExpression="CustomerID" />
<asp:BoundField DataField="Summary" HeaderText="Summary"
SortExpression="Summary" />
<asp:BoundField DataField="DateLogged" HeaderText="DateLogged"
SortExpression="DateLogged" />
<asp:BoundField DataField="DateUpdated" HeaderText="DateUpdated"
SortExpression="DateUpdated" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
<asp:BoundField DataField="Priority" HeaderText="Priority"
SortExpression="Priority" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Surname" HeaderText="Surname"
SortExpression="Surname" />
<asp:BoundField DataField="SkillGroupID" HeaderText="SkillGroupID"
SortExpression="SkillGroupID" />
<asp:BoundField DataField="SkillGroup" HeaderText="SkillGroup"
SortExpression="SkillGroup" />
<asp:BoundField DataField="Expr1" HeaderText="Expr1" SortExpression="Expr1" />
<asp:BoundField DataField="Expr2" HeaderText="Expr2" SortExpression="Expr2" />
<asp:BoundField DataField="NoteID" HeaderText="NoteID"
SortExpression="NoteID" />
<asp:BoundField DataField="ResolutionID" HeaderText="ResolutionID"
SortExpression="ResolutionID" />
</Columns>
</asp:GridView>
Here is my SqlDataSource for the tables join and filtering skills group column for dropdown list
<asp:SqlDataSource ID="ProblemDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT p.ProblemID, p.CustomerID, p.Summary, p.DateLogged, p.DateUpdated, s.Status, pr.Priority, t.Name, t.Surname, sg.SkillGroupID, sg.SkillGroup, ho.Name AS Expr1, ho.Surname AS Expr2, p.NoteID, p.ResolutionID FROM Problem AS p LEFT OUTER JOIN Status AS s ON p.StatusID = s.StatusID INNER JOIN HelpdeskOperator AS ho ON p.HelpdeskID = ho.HelpdeskID LEFT OUTER JOIN Priority AS pr ON p.PriorityID = pr.PriorityID LEFT OUTER JOIN [Skill Group] AS sg ON p.SkillGroupID = sg.SkillGroupID INNER JOIN Technician AS t ON p.ProblemID = t.ProblemID AND s.StatusID = t.StatusID AND pr.PriorityID = t.PriorityID WHERE ([SkillGroup] = #SkillGroup) "
<FilterParameters>
<asp:Parameter Name="newparameter" />
</FilterParameters>
<InsertParameters>
<asp:Parameter Name="SkillGroup" />
</InsertParameters>
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="SkillGroup"
PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
I have also posted a link to the screenshot that displays what the problem is below
http://helios.hud.ac.uk/u0356716/Helpdesk.html
Can someone please advise me on this as it has been bugging me for a while.
Thank you in advance
You've defined your DropDownList in the following way:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
DataSourceID="ProblemDataSource" DataTextField="SkillGroup"
DataValueField="SkillGroup">
<asp:ListItem Selected="True">Hardware</asp:ListItem>
<asp:ListItem Selected="True">Software</asp:ListItem>
<asp:ListItem Selected="True">Network</asp:ListItem>
</asp:DropDownList>
For a start, you can't have all items selected. Only Hardware will be selected as it's the first in the list.
This leads to your second problem;
The query you then run is (reduced for brevity):
SELECT blah
FROM Tables
WHERE ([SkillGroup] = #SkillGroup)
Which, of course, will be Hardware in your example above.
So you will only ever get skill groups of type Hardware back. As it's the data source for your drop down list, you'll therefore only get 'Hardware' in the list.
Note also, you get Hardware twice. This is because you have two records with a SkillGroup of Hardware.
You have a couple of choices here to start with. You can either not make your drop down list databound:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
<asp:ListItem>Hardware</asp:ListItem>
<asp:ListItem>Software</asp:ListItem>
<asp:ListItem>Network</asp:ListItem>
</asp:DropDownList>
Or you can bind your DropDownList to another data source, which simply runs the query:
SELECT DISTINCT SkillGroup FROM [Skill Group]
UPDATE:
For the second part of your question, what you can use the FilterParameters section of SqlDataSource;
<asp:SqlDataSource ID="ProblemDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="YOUR QUERY WITHOUT THE WHERE CLAUSE"
FilterExpression="SkillGroup='{0}'">
<FilterParameters>
<asp:ControlParameter
Name="SkillGroup"
ControlID="DropDownList1"
PropertyName="SelectedValue" />
</FilterParameters>
</asp:SqlDataSource>
Make sure you only DataBind DropDownList1 once, on Page_Init or similar, and don't rebuild it every time (check for !Page.IsPostBack)
However, if you want to query against the datasource everytime (which is more efficient for large data sets), then I suspect the issue here is that your DropDownList value is being wiped out with each PostBack. How are you calling DataBind, and are you remembering, for the DropDownList, to check if !Page.IsPostBack?
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.
I'm selecting table data of the current user:
SELECT [ConfidenceLevel], [LoveLevel], [HappinessLevel] FROM [UserData] WHERE ([UserProfileID] = #UserProfileID)
I have set a control to the unique user ID and it is getting the correct value:
HTML: <asp:Label ID="userID" runat="server" Text="Labeluser"></asp:Label>
C#: userID.Text = Membership.GetUser().ProviderUserKey.ToString();
I then use it in the where clause using the Configure Data Source window
unique ID = control then controlID userID
(fills in .text for me)
I compile and run but nothing shows up where the table should be. Any suggestions?
Here is the code it has created:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ConfidenceLevel" HeaderText="ConfidenceLevel"
SortExpression="ConfidenceLevel" />
<asp:BoundField DataField="LoveLevel" HeaderText="LoveLevel"
SortExpression="LoveLevel" />
<asp:BoundField DataField="HappinessLevel" HeaderText="HappinessLevel"
SortExpression="HappinessLevel" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionStringToDB %>"
SelectCommand="SELECT [ConfidenceLevel], [LoveLevel], [HappinessLevel] FROM [UserData] WHERE ([UserProfileID] = #UserProfileID)">
<SelectParameters>
<asp:ControlParameter ControlID="userID" Name="UserProfileID"
PropertyName="Text" Type="Object" />
</SelectParameters>
</asp:SqlDataSource>
i have answered on the asp.net page as well but in case you dont see that one i'll do it here as well...
take out any reference to "object" the sqldatasource code generates...
it should read:
PropertyName="Text" />
if you have update and insert and delete you'll have to remove it from there as well...
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>