ASP.net DropDownList populates GridView - asp.net

I'm trying to set up the GridView to filter the Credentials that belong to a specific Employee. The dropdownlist provides the list of employees, once selected I want the gridview to only populate entries that belong to the specific employee.
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:DropDownList ID="DropDownListEmployee" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="SelectionHasChanged"
DataSourceID="SqlDataSource2" DataTextField="Fullname"
DataValueField="Employee_ID" AppendDataBoundItems="true"
Width="214px">
<asp:ListItem>Select</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT Employee.F_Name + ' ' + Employee.L_Name AS Fullname, Employee.Primary_Address, Employee.Primary_Phone, Employee.E_mail, Credentials.Degree, Credentials.Years_Experience, Credentials.Certifications, Credentials.Positions, Employee.Employee_ID FROM Employee INNER JOIN Credentials ON Employee.Employee_ID = Credentials.Employee_ID"></asp:SqlDataSource>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource2" DataKeyNames="Employee_ID">
<Columns>
<asp:BoundField DataField="Fullname" HeaderText="Fullname"
ReadOnly="True" SortExpression="Fullname" />
<asp:BoundField DataField="Primary_Address" HeaderText="Primary_Address"
SortExpression="Primary_Address" />
<asp:BoundField DataField="Primary_Phone" HeaderText="Primary_Phone"
SortExpression="Primary_Phone" />
<asp:BoundField DataField="E_mail" HeaderText="E_mail"
SortExpression="E_mail" />
<asp:BoundField DataField="Degree" HeaderText="Degree"
SortExpression="Degree" />
<asp:BoundField DataField="Years_Experience" HeaderText="Years_Experience"
SortExpression="Years_Experience" />
<asp:BoundField DataField="Certifications" HeaderText="Certifications"
SortExpression="Certifications" />
<asp:BoundField DataField="Positions" HeaderText="Positions"
SortExpression="Positions" />
<asp:BoundField DataField="Employee_ID" HeaderText="Employee_ID"
InsertVisible="False" ReadOnly="True"
SortExpression="Employee_ID" />
</Columns>
</asp:GridView>
</asp:Content>

You didn't say what happenes with your current code, but I'm betting that when you select an employee, the page reloads and you get a list of all the employees in your database, right?
If that's true, the reason is because the same SqlDataSource is bound to both your DropDownList and your GridView, and the Select command for the SqlDataSource retrieves all the employees - there is no WHERE criteria to select a desired employee.
I would use 2 SqlDataSources - one for the DropDownList, and one for the GridView. The second SqlDataSource would have a Select command to get the desired employee's information, based on the selection in the DropDownList.
You can modify your SqlDataSource2's SelectCommand to return only the fullname and EmployeeID fields, as you don't need the rest for your DropDownList:
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:DropDownList ID="DropDownListEmployee" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="SelectionHasChanged"
DataSourceID="SqlDataSource2" DataTextField="Fullname"
DataValueField="Employee_ID" AppendDataBoundItems="true"
Width="214px">
<asp:ListItem>Select</asp:ListItem>
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT F_Name + ' ' + L_Name AS Fullname, Employee_ID FROM Employee"></asp:SqlDataSource>
In your second SqlDataSource, you'll need to add a parameter (EmployeeID) to the SelectParameters collection as shown below, and update your SelectCommand to take the parameter.
<asp:SqlDataSource ID="gvDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT Employee.F_Name + ' ' + Employee.L_Name AS Fullname, Employee.Primary_Address, Employee.Primary_Phone, Employee.E_mail, Credentials.Degree, Credentials.Years_Experience, Credentials.Certifications, Credentials.Positions, Employee.Employee_ID FROM Employee INNER JOIN Credentials ON Employee.Employee_ID = Credentials.Employee_ID WHERE Employee.EmployeeID = IsNull(#EmployeeID, EmployeeID)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownListID"
ConvertEmptyStringToNull="true" Name="EmployeeID"
PropertyName="SelectedValue" />
</SelectParameters>
Then assign this SqlDataSource to the GridView instead of the first one.
Note that there is no validation by the SqlDataSource on the values submitted into the parameters - which can be a security threat.
SqlDataSource.Select Method
SqlDataSource.SelectParameters Property

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

if data is exist in gridview then don't show the data in the dropdownlist in ASP.NET

simply i want to hide data in the dropdownlist if this data is exist in gridview
i have gridview that get the datas from database
first data of gridview is "book name".
For example book name is book1
I listed book's name in dropdown list. User is select the book name in the dropdown list and press add button . when user add book1, book1 is written into database and then shown into the gridview , after that in dropdown list, book1 shouldn't appear anymore.
<asp:DropDownList ID="ddlDergi" runat="server" DataSourceID="SqlDataSource1" DataTextField="DERGI_ADI" DataValueField="DERGI_ADI">
</asp:DropDownList>
<asp:RadioButton ID="rbTek" Text="Tek Sefer" Checked="true" GroupName="secim" runat="server" /><asp:RadioButton ID="rbSurekli" Text="Sürekli" GroupName="secim" runat="server" />
<asp:Button ID="btnTalep" runat="server" Text="Talep Et" OnClick="btnTalep_Click" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:BOOKConnectionString %>" SelectCommand="SELECT [DERGI_ADI] FROM [DERGILER]"></asp:SqlDataSource>
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSource2">
<Columns>
<asp:BoundField DataField="KULLANICI_ADI" HeaderText="KULLANICI ADI" SortExpression="KULLANICI_ADI" />
<asp:BoundField DataField="DERGI_ADI" HeaderText="DERGI ADI" SortExpression="DERGI_ADI" />
<asp:BoundField DataField="TEK" HeaderText="TEK" SortExpression="TEK" />
<asp:BoundField DataField="SUREKLI" HeaderText="SUREKLI" SortExpression="SUREKLI" />
<asp:CommandField ShowEditButton="True" />
<asp:CommandField ShowDeleteButton="True" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:BOOKConnectionString %>" SelectCommand="SELECT DERGILER.DERGI_ADI, BAGLANTI.TEK, BAGLANTI.SUREKLI, KULLANICILAR.KULLANICI_ADI FROM BAGLANTI INNER JOIN DERGILER ON BAGLANTI.DERGI_ADI = DERGILER.DERGI_ADI INNER JOIN KULLANICILAR ON BAGLANTI.KULLANICI_ADI = KULLANICILAR.KULLANICI_ADI ">
</asp:SqlDataSource>
DERGI_ADI is our bookname
This is how I would probably do it.
if(gvGridView1.Rows.Count > 0)
{
ddlDropDownList.Items.Remove("Book1");
}
And it sounds like you will want to have it on the drop down list with SelectedIndexChanged event.
Hope this helps.
Please try this one:
if(gvGridView1.Rows.Count > 0)
{
foreach(GridViewRow row in gvGridView1.Rows)
{
ListItem li;
li.Text = row.Cells[1].Text; // you need to identify column number
li.Value =row.Cells[1].Text;// you need to identify column number
if ( ddlDropDownList.Items.Contains(li)==true)
{
ddlDropDownList.Items.Remove(li);
}
}
}

asp .net checkbox inside gridview checked

I have a main 'Products' table and a 'Products_Recommended' table. I want the users to be able to select several products from a GridView using checkboxes and then insert those Product IDs (prodid) into the Products_Recommended table in such a way that a main Product ID is entered (coming from query string) and potentially several recommended ProdIDs get entered. So far so good.
But I need to be able to show the checkboxes to be checked if there were already prodids in the Products_Recommended table previously.
The code below show a 'sqldatasource1' which gets the data from the Products_Recommended table based on query string. I just don't know how the checkboxes can get checked because the GridView has a different sqldatasource binding it.
Thanks!
Meengla
<form id="form1" runat="server">
<asp:GridView ID="Products" runat="server" AutoGenerateColumns="False" DataKeyNames="prodid"
DataSourceID="alldata" EnableModelValidation="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ProductSelector" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="itemnumber" HeaderText="Item Number" SortExpression="itemnumber" />
<asp:BoundField DataField="itemtitle" HeaderText="itemtitle" SortExpression="itemtitle" />
</Columns>
</asp:GridView>
<p>
<asp:Button ID="SelectedProducts" runat="server" Text="Recommend" OnClick="SelectedProducts_Click" />
</p>
<p>
<asp:Label ID="lblProdSelected" runat="server" EnableViewState="False" Visible="False"></asp:Label>
</p>
<asp:SqlDataSource ID="alldata" runat="server" ConnectionString="<%$ ConnectionStrings:dbconnection %>"
SelectCommand="SELECT * FROM Products">
<SelectParameters>
<asp:QueryStringParameter DefaultValue="14" Name="itemid" QueryStringField="itemid"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:dbconnection %>"
SelectCommand="SELECT * FROM dbo.products_recommended WHERE prodid = #itemid)">
<SelectParameters>
<asp:QueryStringParameter DefaultValue="14" Name="itemid" QueryStringField="itemid"
Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
Handle the RowDataBound event, and in the method find the checkbox and set its Checked value.
<asp:GridView ID="Products" OnRowDataBound="GridViewRowEventHandler">
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
var ProductSelector = e.Row.FindControl("ProductSelector") as CheckBox;
ProductSelector.Checked = true;
}
}
You can use the Select method of DataSource to retrieve the data you need

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