Where parameters in EntitydataSource from dropdown control - where-clause

Using the following markup, my details view is not populating when the dropdown is selected.
The id for the where parameter is to come from the dropdwon selected value.It appears that the control parameter is not functioning properly.
<asp:UpdatePanel ID="updtEditContact" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlContacttoEdit" runat="server" CssClass="dropdowns"
AutoPostBack="True" ClientIDMode="Static"/>
<asp:DetailsView ID="dvEditContacts" runat="server" Height="50px" Width="125px"
AutoGenerateEditButton="True" CssClass="mGrid"/>
<asp:EntityDataSource ID="edsSelectedContact" runat="server" ConnectionString="name=webEntities"
DefaultContainerName="webEntities" EnableFlattening="False"
EntitySetName="contacts">
<WhereParameters>
<asp:ControlParameter ControlID="ddlContactToEdit" Name="Id"
PropertyName="SelectedValue" Type="Int32" />
</WhereParameters>
</asp:EntityDataSource>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="rblAddEditContact" EventName="SelectedIndexChanged"/>
<asp:AsyncPostBackTrigger ControlID="ddlContacttoEdit" EventName="SelectedIndexChanged"/>
</Triggers>
</asp:UpdatePanel>

Upon further research, which was tedious as there isn't a lot of the actual EntityDataSource control since all us probably do most of our EF work in the code behind, there were three issues
I did not have a where attribute in the EDS markup
The "Type" in the WhereParameter needs to be DBType
The Name Attribute of the WhereParameter much match the variable in the Where statement in the EDS markup
Here is the code that works:
<asp:UpdatePanel ID="updtEditContact" runat="server">
<ContentTemplate>
<asp:DropDownList ID="ddlContacttoEdit" runat="server" CssClass="dropdowns"
AutoPostBack="True" ClientIDMode="Static"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="rblAddEditContact" EventName="SelectedIndexChanged"/>
</Triggers>
</asp:UpdatePanel>
<br />
<asp:UpdatePanel ID="updatEditContactDetail" runat="server">
<ContentTemplate>
<asp:DetailsView ID="dvEditContacts" runat="server" Height="50px" Width="300px"
DataSourceID="edsSelectedContact" DataKeyNames="Id" Visible="False"
CssClass="mDetail" FieldHeaderStyle-CssClass="fieldheader"
ItemStyle-CssClass="itemvalues" CommandRowStyle-CssClass="cmdRow"
EditRowStyle-CssClass="editvalues" ClientIDMode="Static"
InsertRowStyle-CssClass="insertvalues" RowStyle-CssClass="rowvalues"/>
<asp:EntityDataSource ID="edsSelectedContact" runat="server" ConnectionString="name=webEntities"
DefaultContainerName="webEntities" EnableFlattening="False"
EntitySetName="contacts" Where="it.Id = #ID">
<WhereParameters>
<asp:ControlParameter ControlID="ddlContactToEdit" Name="ID" PropertyName="SelectedValue" DbType="Int32"/>
</WhereParameters>
</asp:EntityDataSource>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="ddlContacttoEdit" EventName="SelectedIndexChanged"/>
</Triggers>
</asp:UpdatePanel>

Related

Multi-parameter SqlDatasource search not returning any records

I have an odd problem. I have a gridview attached to a sqldatasource that I send three possible parameters to. The search works fine if I search the item number but if I search for the first name or last name without the item number it does not return anything. The SQL works fine when I test it in SQL management studio but does not when I test it in visual studio in the search form.
Any assistance in solving this will be appreciated. Thanks for your time.
<table style="width: 100%;">
<tr>
<td>Caller Search</td>
<td>
<asp:Label ID="ITEMsearchlable" runat="server" Text="ITEM#"></asp:Label><br />
<asp:TextBox ID="ITEM_NUMsearch" runat="server"></asp:TextBox></td>
<td>
<asp:Label ID="ofname_label" runat="server" Text="First name"></asp:Label><br />
<asp:TextBox ID="search_fname" runat="server" CssClass="uppercase"></asp:TextBox></td>
<td><asp:Label ID="olname_label" runat="server" Text="Last name"></asp:Label><br />
<asp:TextBox ID="search_lname" runat="server" CssClass="uppercase"></asp:TextBox></td>
<td>
<asp:Button ID="search_btn" runat="server" Text="Offender Caller" /></td>
</tr>
</table>
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="False" AllowPaging="True" AllowSorting="True" Width="771px" EmptyDataText="No record found">
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="ITEM_NUM" HeaderText="ITEM_NUM" SortExpression="ITEM_NUM" />
<asp:BoundField DataField="NAME_FIRST" HeaderText="NAME_FIRST" SortExpression="NAME_FIRST" />
<asp:BoundField DataField="NAME_LAST" HeaderText="NAME_LAST" SortExpression="NAME_LAST" />
<asp:BoundField DataField="CALLER_ID" HeaderText="CALLER_ID" SortExpression="CALLER_ID" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:testdbConnectionString %>"
SelectCommand="SELECT DISTINCT
ORDERS.ITEM_NUM,
ORDERS.NAME_FIRST,
ORDERS.NAME_LAST,
VICTIM_CALL_LOG.CALLER_ID
FROM ORDERS LEFT OUTER JOIN
VICTIM_CALL_LOG ON ORDERS.ITEM_NUM = VICTIM_CALL_LOG.ITEM_NUM WHERE ((ORDERS.ITEM_NUM = #ITEM_NUM)
OR (ORDERS.NAME_FIRST LIKE '%' + #NAME_FIRST + '%') OR (ORDERS.NAME_LAST LIKE '%' + #NAME_LAST + '%'))">
<SelectParameters>
<asp:ControlParameter ControlID="ITEM_NUMsearch" Name="ITEM_NUM" PropertyName="Text" Type="Int32" />
<asp:ControlParameter ControlID="search_fname" DefaultValue="NULL" Name="NAME_FIRST" PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="search_lname" DefaultValue="NULL" Name="NAME_LAST" PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
You need to give the numeric parameter a default value too:
<asp:ControlParameter ControlID="ITEM_NUMsearch" DefaultValue="-1" Name="ITEM_NUM" PropertyName="Text" Type="Int32" />
I used "-1" because I guessed it would never be an actual value in the database, so that needs to be checked.
Note that having a DefaultValue of "NULL" in the string parameters is actually the string "NULL", not the database version of NULL. To do that properly, I suspect that you would have to use code-behind instead of <asp> controls. In the meantime, a default value of "12345" could be a better choice, just in case someone has a name with "null" in it - Null is an actual last name for some people: How does a surname of Null cause problems in many databases?

get Sum of values in column from sqlDataSource

I have a SqlDataSource dsDetails that selects from the DB table.
<asp:SqlDataSource ID="dsDetails" runat="server" SelectCommand="spGetDetails"
OnSelected="dsDetails_Selected" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:QueryStringParameter Name="mode" QueryStringField="mode" Type="String" DefaultValue="NULL" />
</SelectParameters>
</asp:SqlDataSource>
The result is bound to gridview in the aspx page
<asp:GridView CssClass="content" ID="gridDetails" runat="server" DataSourceID="dsDetails" AllowSorting="True" AllowPaging="True" PagerSettings-Position ="TopAndBottom" DataKeyNames="ID" AutoGenerateColumns="False" >
<PagerSettings Position="TopAndBottom" Mode="NumericFirstLast" />
<EmptyDataTemplate>
<b>There are no records to display.</b>
</EmptyDataTemplate>
<Columns>
<asp:BoundField DataField="empNum" HeaderText="Employee Number" SortExpression="empnum" ApplyFormatInEditMode="True" HtmlEncode="False" ReadOnly="True" />
<asp:BoundField DataField="empName" HeaderText="Emplopyee Name" SortExpression="empname" ApplyFormatInEditMode="True" HtmlEncode="False" ReadOnly="True" />
<asp:BoundField DataField="empDoj" HeaderText="Emplopyee Date of joining" SortExpression="empdoj" ApplyFormatInEditMode="True" HtmlEncode="False" ReadOnly="True" />
<asp:TemplateField HeaderText="Salary" SortExpression="sal">
<EditItemTemplate>
<asp:TextBox ID="txtSal" runat="server" Text='<%# Eval("sal", "{0:F}") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server" Text='<%# Eval("sal", "{0:C2}") %>'></asp:Label>--%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<EditItemTemplate>
<asp:Button ID="btnSave" runat="server" CausesValidation="True" CommandName="cmdSave"
Text="Save" />
<asp:Button ID="btnCancel" runat="server" CausesValidation="False" CommandName="cmdCancel"
Text="Cancel" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="btnApprove" runat="server" CausesValidation="False" CommandName="cmdApprove"
Text="Approve" />
<asp:Button ID="btnEdit" runat="server" CausesValidation="False" CommandName="cmdEdit"
Text="Edit" />
<asp:Button ID="btnDelete" runat="server" CausesValidation="false" CommandName="cmdDelete"
Text="Delete" />
<ajaxToolkit:ConfirmButtonExtender ID="cbeDelete" runat="server"
TargetControlID="btnDelete"
ConfirmText="Are you sure?" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now what i have to achieve is Find the Sum of the Salary Column of the grid view. How to achieve this using the Data Source in the page load method? I have to get the sum of Salary for the entire result set (avg records returned 60-80)
Iterating through the rows and computing the sum in gridDetails_RowDataBound wont be effective since the rows.count will be max of 10 since the page size is 10. When the result set has more than 10 records say 55, It will compute the sum for the current gridview page alone (first 10 records). I have to get the sum for all 55 records and display it in a label in the pageload method.
Please provide suggestion..
The SQLDataSource provides a Selected event that fires after data retrieval has finished. See SqlDataSource.Selected Event. You should be able to do a sum on the rows in the grid in this event.
This worked for me
In PageLoad method add
dvSql = DirectCast(dsDetails.Select(DataSourceSelectArguments.Empty), DataView)
For Each drvSql As DataRowView In dvSql
amtSum += CDbl(drvSql("sal"))
Next
lblTotalAmt.Text = CStr(recoveryAmtSum)
In dsDetails_Selected method add this line
e.Command.Parameters("#approvaltype").Value = mode

Multipule information and Pics in multipule gridviews in ASP.NET using VB

I am trying to build a website and am running into a little trouble. My coding knowledge and savvy are armature at best,if you know a better way to do this than please by all means let me know.
On my Featured Bar page I have two gridviews set up. gvPicsRandomBar(For pictures only) and GVRandomBars(For Information only). Each has their own SQLDataSource. I have it set up to where GVRandomBars selects a "random" bar through the SQL TOP command. What I'm trying to do is get the gvPicsRandomBar to display a picture of the same "random" bar that is selected by GVRandomBars. Both gridviews are querying from the same table but with different SELECT statements as each gridview is concerned with different items in the same table row.
I thought I had somewhat accomplished this by reading the primary key from the GVRandomBars and placing that value in a Label(lblRandomBar) that I use as a control for gvPicsRandomBar to match up the correct pic to display in it's own gridview as they both query the same database, but I was wrong. Whenever I startup my website I get this error "Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index". I'm just not sure where to place this code i.e. (Event) lblRandomBar.Text = GVRandomBars.DataKeys(0).Value.ToString() so that I will not get the above error.
Seperate problems if by miracle I get it to work
One problem I have is that it appears that the value of the primary key is not passed on to lblRandomBar.text. I assume this is because I do not know where to correctly place the code lblRandomBar.Text = GVRandomBars.DataKeys(0).Value.ToString()The other problem I do have when I sometimes get it to work is that the picture displayed in gvPicsRandomBar is one step behind from when I click the search button. Example, I click search for city "Austin" in my dropdown list which could potentially give me a primary key value of 45. The picture for that primary key is not displayed until I click search for another city in the dropdown list and the page posts back to the server.
The value of the primary key is in lblRandomBar.text for the current bar displayed in the GVRandomBars but the picture of the bar associated with that recored does not appear in the gvPicsRandomBar until the search button is clicked and another "random" bar is displayed in the GVRandomBars. So I am looking at a picture in gvPicsRandomBar from the last bar that was brought up in GVRandomBars while another bars information is currently displayed in GVRadnomBars.
I am looking to have the same bar information and bar picture in both gridviews at the same time, and not one step behind like I have currently with the picture in gvPicsRandomBar. Any help would be greatly appreciated. Thanks.
ASP.NET HTML
<%# Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site.Master" CodeBehind="Random Bar.aspx.vb" Inherits="RGVHappyHour.Featured_Bar" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
<center><h2>Random Bar</h2></center>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<p>
<asp:GridView ID="gvPicsRandomBar" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="Number,Bar Name,Image" DataSourceID="SqlDataSourceRandomBarPics" ForeColor="#333333" GridLines="None" HorizontalAlign="Center" Width="548px">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:ImageField DataImageUrlField="Image" HeaderText="Image" NullDisplayText="No Picture">
</asp:ImageField>
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSourceRandomBarPics" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionStringBars %>" SelectCommand="SELECT * FROM [Bars] WHERE ([Number] = #Number)">
<SelectParameters>
<asp:ControlParameter ControlID="lblRandomBar" Name="Number" PropertyName="Text" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</p>
<p>
<asp:GridView ID="GVRandomBars" runat="server" AutoGenerateColumns="False" DataSourceID="SqlDataSourceRandomBar" Width="548px" CellPadding="4" ForeColor="#333333" GridLines="None" AllowPaging="True" DataKeyNames="Number" SelectedIndex="0">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="Bar_Name" HeaderText="Bar Name" SortExpression="Bar_Name" />
<asp:BoundField DataField="Addresss" HeaderText="Addresss" SortExpression="Addresss" />
<asp:BoundField DataField="Phone_Number" HeaderText="Phone Number" SortExpression="Phone_Number" />
<asp:BoundField DataField="Days" HeaderText="Days" SortExpression="Days" />
<asp:BoundField DataField="Happy_Hour" HeaderText="Happy Hour" SortExpression="Happy_Hour" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle ForeColor="#333333" BackColor="#F7F6F3" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSourceRandomBar" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionStringBars %>" SelectCommand="SELECT TOP (1) [Number], [Bar Name] AS Bar_Name, Addresss, [Phone Number] AS Phone_Number, Days, [Happy Hour] AS Happy_Hour, [Image] AS Image FROM Bars WHERE (City = #City) ORDER BY NEWID()">
<SelectParameters>
<asp:ControlParameter ControlID="ddlCity" Name="City" PropertyName="SelectedValue" />
</SelectParameters>
</asp:SqlDataSource>
<p>
<table class="style1" style="width: 100%">
<tr>
<td style="width: 220px; text-align: right;" class="style2">
<asp:Label ID="lblCity" runat="server" Text="City:" Font-Size="Large"
ForeColor="#47C2FF"></asp:Label>
</td>
<td style="width: 135px">
<asp:DropDownList ID="ddlCity" runat="server" DataSourceID="SqlDataSourceCity"
DataTextField="City" DataValueField="Number">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSourceCity" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionStringBars %>" SelectCommand="SELECT * FROM [City] ORDER BY [City]"></asp:SqlDataSource>
</td>
<td style="width: 220px; position: relative; text-align: left; vertical-align: middle;">
<asp:Button ID="btnCitySearch" runat="server" Text="Search" />
</td>
</tr>
<tr>
<td style="width: 220px" class="style2" draggable="true">
<asp:Label ID="lblRandomBar" runat="server"></asp:Label>
</td>
<td style="width: 135px">
</td>
<td style="width: 220px">
</td>
</tr>
</table>
</p>
</asp:Content>
Code Behind Random Bar.aspx.vb
Public Class Featured_Bar
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
End Sub
Protected Sub btnCitySearch_Click(sender As Object, e As EventArgs) Handles btnCitySearch.Click
End Sub
Protected Sub GVRandomBars_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GVRandomBars.SelectedIndexChanged
End Sub
Protected Sub btnCitySearch_DataBinding(sender As Object, e As EventArgs) Handles btnCitySearch.DataBinding
lblRandomBar.Text = GVRandomBars.DataKeys(0).Value.ToString()
End Sub
End Class

How to use current item id in SPGridview

Can you please tell me how do i use current item id in the NavigateURL in SPGridView.
Below is the code sample. If I use Eval it is giving run time error.
Please help me in this case..
<SharePoint:SPGridView runat="server" ID="gdvSearchResults" width="50%" AllowSorting="True"
AutoGenerateSelectButton="false" AutoGenerateColumns="false">
<Columns>
<SharePoint:SPBoundField runat="server" DataField="Attachments" HeaderText="Attachments" SortExpression="Attachments" />
<SharePoint:SPBoundField runat="server" DataField="Practice" HeaderText="Practice" />
<asp:HyperLinkField DataTextField="ID" HeaderText="Require_x0020_Details_x0020__x00" NavigateUrl="http://server/sites/TestingCollection/TestLists/Send%20Mail/EditForm.aspx?ID="+ID/>
</Columns>
</SharePoint:SPGridView>
Thanks in advance!
Resolved it using the below changes in my grid.
<SharePoint:SPGridView runat="server" ID="gdvSearchResults" width="50%" AllowSorting="True"
AutoGenerateSelectButton="false" AutoGenerateColumns="false">
<Columns>
<SharePoint:SPBoundField runat="server" DataField="Attachments" HeaderText="Attachments" SortExpression="Attachments" />
<SharePoint:SPBoundField runat="server" DataField="Practice" HeaderText="Practice" />
<asp:HyperLinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="~/EditForm.aspx?ID={0}" DataTextField="ID" HeaderText="ID" />
</Columns>
</SharePoint:SPGridView>

Linkbutton in a Datalist in a GridView

I have an interesting ASP/VB.NET problem. I have a gridview where each row has its own datalist in a template column. I want to add to each item in the datalist a linkbutton that will trigger an event based on data in the datalist. But I'm not sure how to do it. It's in a project so it has the designer file which does list the gridview but not the datalist inside the gridview. When I try to add it, the listing for the datalist is removed later on when I compile.
My question is now do I get the linkbutton in the datalist in the gridview to do something?
<asp:GridView ID="gvCmteNom" runat="server" AutoGenerateColumns="False" showheader="true" HeaderStyle-BackColor="Silver" Width="1600px">
<Columns>
<asp:TemplateField HeaderText="CURRENT SERVICE">
<ItemTemplate>
<asp:TextBox ID="txtID" runat="server" Text='<%# Bind("NOMINEE_ID") %>' Visible="False" Width="25px" />
<asp:DataList ID="dlCurrentCmtes" runat="server" DataSourceID="dsCurrentCmte" RepeatLayout="Flow" DataKeyField="ID" RepeatDirection="Horizontal">
<ItemTemplate>
<asp:HiddenField runat="server" ID="hdnUserID" Value='<%# Eval("ID") %>' />
<asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description") %>' />
<asp:LinkButton runat="server" ID="lbIncrementYear" CommandName="IncrementYear" CommandArgument='<%# Eval("ProductID") %>' Text="Add Year" />
</ItemTemplate>
<SeparatorTemplate><br /><br /></SeparatorTemplate>
</asp:DataList>
<asp:SqlDataSource ID="dsCurrentCmte" runat="server"
ConnectionString=""
ProviderName="System.Data.SqlClient" SelectCommand="spCmteList" SelectCommandType="StoredProcedure">
<SelectParameters>
<asp:ControlParameter ControlID="txtID" Name="ID" PropertyName="Text" Type="String" DefaultValue="" />
</SelectParameters>
</asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Two options:
Option 1
Specify the ItemCommand event handler for the DataList and use that to respond to the event:
<asp:DataList OnItemCommand="Item_Command" />
Then specify that function in the code behind:
Sub Item_Command(sender As Object, e As DataListCommandEventArgs)
If e.CommandName = "IncrementYear" Then
...
End If
End Sub
Option 2 Specify the OnClick eventhandler for the link button
<asp:LinkButton OnClick="LinkButton_Click" runat="server"/>
Then
Sub LinkButton_Click(sender As Object, e As EventArgs)
...
End Sub