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().
Related
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.
I've tried hard to make sure I couldn't find the answer to this anywhere, so apologies if it's a repeat.
I want to use a WHERE clause to filter data output from an SQL Server statement to items which are less than two weeks old. I've successfully managed to write the .vb code to get the date from two weeks ago, however I'm having trouble trying to insert this date into the statement from my .aspx page.
The code to calculate the date two weeks ago is as follows:
Protected dateBuffer As String = lastFortnight().ToString("dd/MM/yyyy")
Function lastFortnight() As DateTime
Dim retVal As DateTime = DateTime.Now.AddDays(-14)
Return retVal
End Function
This returns a date of 06/01/2014 (as of today) if called on my .aspx page using <%=dateBuffer %>
However if I try and insert it into my SQL statement to filter the outputs like so:
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:Database SQL 20130905ConnectionString %>"
ProviderName="<%$ ConnectionStrings:Database SQL 20130905ConnectionString.ProviderName %>"
SelectCommand="SELECT [ReqNumber], [ApprovedDate], [Approved] FROM [RequisitionDetails] WHERE ([RequestDate] >= ?)">
<SelectParameters>
<asp:Parameter DefaultValue='<%=dateBuffer %>' Name="RequestDate" Type="DateTime" />
</SelectParameters>
</asp:SqlDataSource>
I consistently get the error
Exception Details: System.FormatException: String was not recognized as a valid DateTime.
I've spent most of my day searching for how to fix this, and I'm still no closer than I was 4 hours ago. If I'm making any stupid mistakes please let me know... I'm a complete newbie when it comes to any of this stuff, It's the first time I've ever worked with .aspx, .vb and SQL server.
SQL's date format differs from the .NET DateTime data type, which is why you're getting the formatting error. There are ways to convert, such as using the SqlDateTime struct - How can I convert a .Net Datetime to a T-SQL Datetime
In your case though, might it not be simpler to pass the number of days to your SQL statement (or stored proc), and use a DateDiff/DateAdd combination in SQL ?
I've created the survey form but I don't know how to continue doing the database...
Can someone each me?
Anyway, Here's my code:
<tr>
<td class="auto-style2">5) Would you share our website to your friends?</td>
<td>
<asp:RadioButtonList ID="rbl5" runat="server" AutoPostBack="True" RepeatDirection="Horizontal" RepeatLayout="Flow">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td class="auto-style2">6) Any comments or suggestions?</td>
<td>
<asp:TextBox ID="tbComment" runat="server" Height="182px" TextMode="MultiLine" Width="271px"></asp:TextBox>
<br />
<br />
<br />
<input type="button" onclick="btnSubmit_Click()" value="Submit" />
<asp:Button ID="btnReset" runat="server" OnClick="btnReset_Click" Text="Reset" />
</td>
</tr>
</table>
</div>
</form>
As you noticed, I used radiobuttonlist and comment box. These are the reasons why I'm having problem to create the database... Please teach me...I only know how to create tables for database...
And the database might be something like this...
This is the QUESTION Table:
CREATE TABLE [dbo].[Question]
(
[Id] INT NOT NULL PRIMARY KEY,
[Question] NCHAR(10) NULL,
[Options] NCHAR(10) NULL
)
This is the ANSWERS Table:
CREATE TABLE [dbo].[Answers]
(
[Id] INT NOT NULL PRIMARY KEY,
[QuestionId] NCHAR(10) NULL,
[Answers] NCHAR(10) NULL
)
And I'm also not sure about the NCHAR(10) ...
So this is how bad I am in programming.
Please teach me.
If you don't have experience with SQL, you could try parse.com, just to get something up and running quick.
You'll have to read through their docs, they also have tutorials and a quickstart explanation.
I would still recommend learning about SQL, simply because you don't really need to know that much to get going.
you need to use database servers like sql or ms-sql or oracle or other database engines unless u are asking query to create the database, which i assume not, as there is no query or other related tags in your question
If you have access to a SQL Server (SQLExpress, LocalDB, Full MSSQL) and you are able to make use of EF (Entity Framework), then you can use Code First to build your Database from your domain models.
EF Code First Tutorial
Assuming you're running Windows, SQLExpress and LocalDB should already be installed on your PC, if not they can be downloaded here. Either of these will suffice for what you are looking to do and both are free. You could alternatively pay for a fully featured MSSQL license, however, this might be overkill for you currently.
All of these will happily run on your local machine, if however you are looking to deploy your application to the Internet, you may want to considering some sort of hosting option unless you are comfortable with doing so yourself.
Currently, I'm populating a DropDown with the following SQL:
SELECT REPORT_DATE FROM MY_TABLE
Although the values stored in the table are in the following format, dd-mon-yyyy (my preferred format), the text that fills my DropDown differs in that it also displays time, like dd-mon-yyyy hh:mm:ss AM.
What is the best way to resolve this? I know of TRUNC and TO_DATE functions in Oracle SQL. But I think I could also loop through the DropDown after its populated and truncate the string there. I have tried the following code, but it returns a runtime error:
For Each i As ListItem In DropDown1.Items
'Strip time here
i.Text.ToString("dd-MMM-yyyy")
Next
Essentially, I just want to loop my DropDown and change ONLY the text to match `dd-MMM-yyyy'. How can I accomplish this? Should I use SQL or VB.NET? Is there a best practice?
Thank you!
you can do this sql side with
SELECT to_char(REPORT_DATE, 'dd-mon-yyyy') report_date FROM MY_TABLE order by report_date;
p.s.
"values stored in the table are in the following format, dd-mon-yyyy". dates are not stored like that, they are stored as an 7 byte numeric internally, how you see them on select is entirely dependant on your NLS_DATE_FORMAT setting.
If the data is of type DateTime, you can simply specify the DataTextFormatString property on the dropdown as so:
<asp:dropdownlist DataTextFormatString ="{0:MM-dd-yyyy}" ... />
It should be to the UI layer to display the date in the format you want. You should try to avoid putting the logic to transform the date to the format you want on the SQL statement, if possible.
Use this string to get data from Oracle
SELECT TO_CHAR(REPORT_DATE,'DD-MON-YYYY') FROM MY_TABLE
Try
i.Text = Convert.ToDateTime(i.Text).ToString("dd-MMM-yyyy")
You cannot use .ToString("dd-MMM-yyyy") for date formatting on string. You need to convert it to DateTime
You can also try <asp:DropDownList DataTextFormatString="{0:dd-MMM-yyyy}" />
It's better to format the date in the DropDownList instead of letting sql doing it.
Just add DataTextFormatString="{0:dd/MM/yyyy}" to your DropDownList tag :
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="adddate"
DataTextFormatString="{0:dd/MM/yyyy}" DataValueField="adddate">
</asp:DropDownList>
I have a gridview with 3 columns, in database the date field of the origin table isn't stored as a date format (the table is in oracle), is stored in string format, so I have my datasource in asp like this
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConflictDetection="CompareAllValues"
ConnectionString="<%$ ConnectionStrings:OracleXexdb %>"
ProviderName="<%$ ConnectionStrings:OracleXexdb.ProviderName %>"
SelectCommand="select to_date(date, 'mm/dd/yyyy') as date, user, description from mytable where user is not null"
filterexpression = "user LIKE '%{0}%'"
>
</asp:SqlDataSource>
As you can see in the SelectCommand, I convert the date field with the format dd/mm/yyyy (in the database the date format is mm/dd/yyyy); when I run my webpage in the asp.net development server everything is fine, I mean I see the date field with the format dd/mm/yyyy but when I put the webpage on the server I see the mm/dd/yyyy format.
Is there anything I can do? thanks in advance
The most likely reason for the difference when deploying the application is that the culture that will be picked up will be different.
Setting the culture explicitly to the needed one in the Web.config file system.web globalization configuration or on the current thread should resolve the problem.
For example: See Example in Comment Below
The date format can also be specified explicitly on the DatePicker by using the Format method.