ASP.NET vb use databound variable in SQL statement - asp.net

I have a data repeater that lists accounts in a sql data table. In another tablet is transactions with the account name and an amount for the transaction. I use the following code for the repeater.
<asp:Repeater ID="Repeater2" runat="server" DataSourceID="SqlDataSource2">
<ItemTemplate>
<div> <strong><%# Eval("Account")%> </strong></div>
<div> <%# Eval("Type")%> </div>
</ItemTemplate>
</asp:Repeater>
Now I want to make another sql statement that will be in each block of the repeater to add the account total (sum of all transactions for that account. I don't know how to format the sql statement. something like:
"SELECT SUM(Amount) FROM Transactions WHERE ([Account] LIKE '%' + #Account + '%')"

The best is to modify the sql stqtement of your SqlDataSource2 to include the "sum of all transactions for that account".
This will give something like this:
Select u.Account, u.Type, count(t.Account) as NumberTransactions
From User u inner join Transactions t on u.Account = t.Account
I don't know the exact name of your tables so this is just an example.
After that, for your Repeater you have the Account, Type and NumberTransaction from the same datasource.

Related

SQL Query to retrieve date adds time to value?

Having a bit of trouble with my SQL query.
I am retrieving a value from my SQL database, where it has the date of when a person was added as a life member. The column type is "date" rather than varchar as i couldnt organise by date if it was just a string.
The value of "DateInducted" is just a simple date such as "01/05/1963"
In the query builder for Visual Studio, I have tested my SQL Statement (which is below) and appears exactly as i want
"SELECT [DateInducted], [Name] FROM [LifeMembers] ORDER BY [DateInducted] DESC"
However when the Website is loaded, the value is
5/26/2012 12:00:00 AM
Where is it getting the time from? Is there a way to stop this? All i need is the date.
Thinking this is just a simple oversight on my part, but Google searches didnt provide the correct answer. According to W3 schools site, Date type should just give me the date?
Thanks in Advance
Edit:
Page Code now attached
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<h2>Lifemembers</h2>
<table class="DataTable">
<asp:Repeater ID="rptLifemembers" runat="server" DataSourceID="dsLifeMembers">
<HeaderTemplate>
<tr class="DataTableHeader">
<td style="min-width:40%"><strong>Date Inducted</strong></td>
<td style="min-width:60%"><strong>Member</strong></td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr class="DataTableRow">
<td style="min-width:40%"><strong><%#Eval("DateInducted")%></strong></td>
<td style="min-width:60%"><%#Eval("Name")%></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
<asp:SqlDataSource ID="dsLifeMembers" runat="server"
ConnectionString="<%$ ConnectionStrings:SPEEDWAYConnectionString %>"
SelectCommand="SELECT [DateInducted], [Name] FROM [LifeMembers] ORDER BY [DateInducted1] DESC">
</asp:SqlDataSource>
You can either convert the date to varchar in the query or format the output in asp.net.
If you choose to do it in the query you can use the function Convert:
SELECT CONVERT(varchar(50),[DateInducted], 101) DateInducted, [Name] FROM [LifeMembers] ORDER BY [DateInducted] DESC
Add a format string to your binding expression:
<%#Eval("DateInducted", "{0:d}")%>
The datetime data type in SQL and the Date type in CLR always hold both a date and a time. In order to display one or the other and not both when converting to string, you need to use a format string or Date built-in string conversion functions such as ToShortDateString().

ddl Selected Value invalid error

I have a drop down list inside of a DataList EditItemTemplate, fueled by a SQLDataSource (below). The parameter #panelid is being set in codebehind on the SQL databinding event, and that seems to be working fine. Contents are accurate and what I expected.
Then I tried setting the selected value using Bind("scopeid"), which should be fine. scopeid and equipmentid are related, in fact scopeid is populated by equipmentid in the footer of this same datalist, so their values should be matching (and they are). This should push the scopeid of the chosen record to the selected item in the ddl. However, I get the 'ddlEquipment' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value error when switching to my EditItemTemplate. Any ideas?
<asp:DropDownList class="smallInputddl" ID="ddlEquipment" runat="server" DataSourceID="sqlEditEquipment" SelectedValue='<%# Bind("scopeid")%>' DataTextField="modelnumber" DataValueField="equipmentid" AppendDataBoundItems="true">
</asp:DropDownList>
<asp:SqlDataSource ID="sqlEditEquipment" runat="server" OnDataBinding="sqlEditEquipment_DataBinding" ConnectionString="<%$ ConnectionStrings:ProductionDatabaseConnectionString1 %>"
SelectCommand="select * from tblsls_equipmentscope where proposalnumber in (select proposalnumber from tblsls_cntrlpanel where id = #panelid)">
<SelectParameters>
<asp:Parameter Name="panelid" />
</SelectParameters>
</asp:SqlDataSource>
To demonstrate, here's a Sql query to show the relationship between scopeid and equipmentid. tblsls_cntrlvfd also has the id from tblsls_cntrlpanel.:
select e.equipmentid, c.scopeid from tblsls_equipmentscope e
left join tblsls_cntrlvfd c on e.equipmentid = c.scopeid
where proposalnumber in (select proposalnumber from tblsls_cntrlpanel where id = 20)
Results:
equipmentid scopeid
----------- --------
9513 9513
9541 9541
9543 NULL
(3 row(s) affected)
The gist is that the equipment exists off in it's own little world, and controls in it's. Both get tied to a proposal. There's also a VFD that is associated to both a control panel and a specific piece of equipment.
You'll need to include a 'blank' option in your DDL for it to match the null value to. It's trying to find a match in the list to the cell's original value(null) but since that isn't an available option it's throwing the exception. Just set index 0 of your DDL to be blank.
Figured it out. I'm in the habit of keeping SQL data sources that just fuel a drop down list right with the list they populate. Usually this is desired. In this situation, keeping it with the list resulted in me having to use a work around to set it's parameter's value. It could not see the label it needed to from where it was, so I was setting the default value in the data sources Databinding event. This works fine on it's own, and the list populates as expected. As soon as you try to set the SelectedValue however, when the datasource is having it's parameters setup in databinding, what happens is a slight loading out of order issue. These eventually wind up running at the same time, so the datasource hasn't run and populated it's dataset yet, SelectedValue sees a set with 0 entries in it.
Moving the SQLDataSource out so that it could see the control I originally wanted it to solved the issue. It no longer needed to have it's parameter set through code, it's list is essentially static.

ASP.NET GridView OnDataBound Sort in Code Behind

I have a GridView where one of the columns/fields has checkboxes; the checkboxes are checked or unchecked, based on a sub-query from the code behind, while the container GridView is bound to a SqlDataSource. What I want to be able to do is that once the GridView is databound then make it sort by the state of checkboxes: All rows with checkboxes checked appear on the top of grid. Here is part of my GridView:
<ItemTemplate>
<asp:CheckBox ID="ProductSelector" runat="server" Checked='<%# ShowCheckMarks(DataBinder.Eval(Container.DataItem,"prodid").ToString()) %>' />
</ItemTemplate>
I am thinking that I can call the GridView's Ondatabound event and someone make it sort from there?
Thanks.
If that is the only row that you need to sort by why not just add an order by to the sql query you're using to pull the data?
You can save yourself a lot of work if you
store the state of checkbox in database
. That way you can easily set a sort expression on the template field.
Edit
You can do this on clientside via jQuery tablesorter but it might be a
bit too much of work Check this.
Again I think you can somehow manipulate the query to achieve this.
Try this
SELECT dbo.Products.*, dbo.products_recommended.* FROM dbo.Products INNER JOIN dbo.products_recommended ON (dbo.Products.prodid = dbo.products_recommended.prodid) WHERE dbo.Products.prodid IN (dbo.products_recommended.prodid) AND (dbo.Products.prodid = " + itemid + " order by dbo.Products.prodid desc )"
Please note : Never use a
select a.* from YourTable a
This will select all columns from your table & may bring a serious problem later on. Only query the columns you want like
select a.column1,a.column2 from YourTable a
SELECT dbo.Products.prodid,
dbo.Products.itemtitle,
dbo.Products.itemnumber,
dbo.Products.image_1,
CAST(ISNULL(dbo.products_recommended.recommendedid, 0) as BIT) as recommendedid
FROM dbo.Products LEFT OUTER JOIN dbo.products_recommended
ON (dbo.Products.prodid = dbo.products_recommended.prodid)
WHERE dbo.Products.prodid IN (dbo.products_recommended.prodid)
AND (dbo.Products.prodid = #itemid)
The left outer join will make sure it pulls all items from the Products table while only pulling matching items from the products_recommended table. It will also convert the recommendedid to a BIT value which should work with the checkboxes
Like the good helpers here suggested, I needed to have main sql query to populate the GridView to sort the records, instead of a different query in the code behind. So now the Declarative SqlDataSource syntax is the following. This solves the problem.
I learned a few hew things from the feedback here. Thank you all!
SELECT DISTINCT Products.prodid,
Products.itemtitle,
Products.itemnumber,
Products.image_1,
CASE WHEN YESNO IS NULL THEN CAST(0 AS BIT) ELSE CAST(1 AS BIT) END AS CheckUncheck
FROM Products
LEFT OUTER JOIN (SELECT prodid_recommended as YESNO FROM products_recommended
WHERE #itemid IN (prodid) ) A
ON Products.prodid = A.YESNO
ORDER BY CheckUncheck DESC

Columns of two related database tables in one ASP.NET GridView with EntityDataSource

I have two SQL Server tables with Primary Keys (PK) and a Foreign Key (FK) linking the two tables:
1) Table "Order"
OrderID, int, PK
AddressID, int, FK
...
2) Table "Address"
AddressID, int, PK
City, nvarchar(50)
...
Then I've created an (ADO.NET) Entity Data Model out of those two tables.
Now on my (ASP.NET) webpage I put a GridView with an EntityDataSource. In my GridView I want to display two columns:
OrderID
City (belonging to that order and linked by the AddressID-key)
How can I do that? My problem is: When I configure the Entity Data Source I can select an "EntitySetName" which can be
either "Order" or "Address" but not both, nor can I select any kind of relationship. If I select "Order" as EntitySetName
then in the GridView I can add the columns
OrderID
Address
Address.AddressID
Adding the column "Address" displays empty cells. Adding "OrderID" and "Address.AddressID" displays the expected IDs. But how can I
add the "City" of the related address to my GridView?
Thank you for help in advance!
Edit: Clarification:
The Entity Framework has created a class "Order" and a class "Address" corresponding to the database tables. The class "Order" has a reference to an "Address" object as a navigation property, corresponding to the 1-n relationship between Address and Order table.
Basically I want to have a column in my GridView which displays Order.Address.City. I have tried to add a bound field with "Address.City" as data field to the GridView but it results in a runtime error ("no such property...").
OK, much too many hours later I found the solution myself:
Option 1:
It is possible to use the select property in the EntityDataSource which allows to create arbitrary projections of data from several related entities/database tables (in my case: OrderID from Order entity and City from the
Address entity)
Drawback: Using select in the EntityDataSource makes using Insert, Update and Delete in the GridView impossible!
Option 2:
The EntityDataSource must have the include property to include the related address property along with the queried orders. The markup looks likes this:
<asp:EntityDataSource ID="EntityDataSourceOrders" runat="server"
ConnectionString="name=MyEntitiesContext"
DefaultContainerName="MyEntitiesContext"
EntitySetName="Order" Include="Address"
EnableDelete="True" EnableInsert="True"
EnableUpdate="True">
</asp:EntityDataSource>
Then the columns collection of the GridView can have a template field like this:
<asp:TemplateField HeaderText="City" >
<ItemTemplate>
<asp:Label ID="LabelCity" runat="server" Text='<%# Eval("Address.City") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
Here Eval is important. Bind does not work. Also using a BoundField as a column...
<asp:BoundField DataField="Address.City" HeaderText="City" />
... is NOT possible. So it is not possible in the GridView to edit the City (which makes sense because its a related field belonging to another table and perhaps to many other orders). But it is possible to edit flat fields of the order entity and also the "AddressID" of the order to assign another address.

Dynamically built SelectCommand for GridView SqlDataSource in asp.net

I'm working with a GridView that uses a SqlDataSource element that looks like this:
<asp:SqlDataSource ID="InventoryDB" runat="server" ConnectionString="<%$ ConnectionStrings:InventoryConnectionString %>"
SelectCommand="SELECT [Server], [Customer] FROM [Website] WHERE [Owner] = 'someOwner'">
</asp:SqlDataSource>
I'd like to replace the 'someOwner' part of the where clause with something dynamic, like so:
SelectCommand="SELECT [Server], [Customer] FROM [Website] WHERE [Owner] = '<%# UserManager.getCurrentUser(Request) %>'"
But when I do this, it seems to use the literal text of the WHERE clause instead of evaluating my function call, which of course does not work. What is the right way to do this?
The proper way to handle that is to use parameters. The MSDN documentation on it is pretty thorough in showing how to use them.
User Parameters with Data Source Controls has some more detailed and accessible information on using parameters.

Resources