asp .net checkbox inside gridview checked - asp.net

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

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 DropDownList populates GridView

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

How to bind dropdownlist in EditItemTemplate in FormView control?

Using Visual Web Developer Express 2010 with ASP.NET 4.0.
I have a FormView and I want to set a default value from the database. I can't get it to bind to the value in the database. My FormView looks like this:
<asp:FormView
ID="frmOrderDetails"
DataSourceID="sdsFormOrderDetails"
runat="server"
DataKeyNames="orderId">
<EditItemTemplate>
<h3>Edit Order Details</h3>
<asp:Label ID="lblStrategy" Text="Strategy:" AssociatedControlID="ddlStrategies" runat="server" />
<asp:DropDownList SelectedValue='<%# Bind("strategyId") %>'
ID="ddlStrategies"
runat="server"
DataTextField="strategy"
DataValueField="strategyId"
DataSourceID="sdsStrategies"
/>
<asp:LinkButton
id="lnkUpdate"
Text="Update Order"
CommandName="Update"
Runat="server" />
|
<asp:LinkButton
id="lnkCancel"
Text="Cancel"
CommandName="Cancel"
Runat="server" />
</EditItemTemplate>
</asp:FormView>
<asp:SqlDataSource ID="sdsFormOrderDetails" runat="server"
ConnectionString="<%$ ConnectionStrings:LocalSQLServer %>"
ProviderName="<%$ ConnectionStrings:LocalSQLServer.ProviderName %>"
SelectCommand="usp_GetOrderDetails" SelectCommandType="StoredProcedure"
UpdateCommand="usp_UpdateOrder" UpdateCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter Name="orderId" ControlID="grdOrders" PropertyName="SelectedDataKey.Value" />
</SelectParameters>
<UpdateParameters>
<asp:ControlParameter Name="orderId" ControlID="grdOrders" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:SqlDataSource ID="sdsStrategies" runat="server"
ConnectionString="<%$ ConnectionStrings:LocalSQLServer %>"
ProviderName="<%$ ConnectionStrings:LocalSQLServer.ProviderName %>"
SelectCommand="usp_GetStrategiesDropDown">
</asp:SqlDataSource>
The EditItemTemplate does not even load when I click the edit button on my FormView control, but I don't get an error message either.
You need to do the following to bind a DropDownList to the EditItemTemplate:
Add the DropDownList and its DataSource to the EditItemTemplate.
Set the DropDownList parameters:
DataSourceID="SqlDataSourceDropDownlist" SelectedValue=<%# Bind("ValueToBind") %>
DataTextField="ValueToDisplay" DataValueField="ValueToBind"
Set the ListView / FormView DataSource <UdateParameters>: <asp:Parameter Name="RankID" Type="Int32" />
you need to use formview Databound event like
protected void frmOrderDetails_DataBound(object sender, EventArgs e)
{
if (frmOrderDetails.CurrentMode == FormViewMode.Edit)
{
DropDownList ddlStrategies = (DropDownList)frmOrderDetails.FindControl("ddlStrategies");
ddlStrategies.SelectedValue = Your DB Value Goes here;
}
}

ASP.NET configure data source is not returning anything?

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...

Resources