Please see the database DDL below:
create table datetest (datetime1 datetime)
insert into datetest values(getdate())
Please see the presentation code below:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# bind("datetime1") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
The output on the page is: 11/04/2013 19:51:40, but the database value is: 2013-04-11 19:51:40.017 (notice the milliseconds are chopped off the first value).
I have looked into this and have found a number of posts on here, which suggest using EVAL and String.Format, but I have been unsuccessful. How can I display milliseconds on the webpage?
I have tried the following code:
<asp:Label ID="Label1" runat="server" Text='<%
Eval("datetime1").ToString("dd/MM/yyyy hh:mm:ss.fff") %>'></asp:Label>
However, I am prompted with an exception: "Conversion from string "dd/MM/yyyy" to type 'Integer' is not valid."
<asp:Label ID="Label1" runat="server" Text='<%# Eval("datetime1").ToString("dd/MM/yyyy hh:mm:ss.fff") %>'></asp:Label>
Something like that should do it. If you need help with custom time formats, have a look here: http://msdn.microsoft.com/en-gb/library/8kb3ddd4.aspx
You do not need to do a template to change the format though, you can add {0:dd/MM/yyyy hh:mm:ss.fff} in the custom format property
You should use Eval with additional format parameter instead of Eval().ToString() call:
<asp:Label ID="Label1" runat="server"
Text='<%# Eval("datetime1", "{0:dd/MM/yyyy hh:mm:ss.fff}") %>'></asp:Label>
Related
I have an aspx page with a few FormViews and an updateable GridView that I would like to add validation for. The fields that I am trying to validate are also using the CalendarExtender from the AJAX Control Toolkit by the way. I am trying to use the RequiredFieldValidator and RangeValidator for this. The problem is I don't see any errors from within VisualStudio 2015 while adding the validators. But when I run debug mode and click the button to open a FormView that contains validation I get a 500 error without any useful information to find/fix my problem.
I first tried adding both of the validators at once but after having problems, I am just trying to get the RequiredFiledValidator working. But I still need to know how to get the RangeValidator to work properly. For the RangeValidator, I want to validate a start date of no less than today and an end date that is greater than the start date. I tried using all of the examples that I found on these pages:
[1] https://www.c-sharpcorner.com/UploadFile/17e8f6/requiredfieldvalidator-control-in-Asp-Net/
[2] https://asp.net-tutorials.com/validation/required-field-validator/
[3] http://www.java2s.com/Tutorial/ASP.NET/0160__Validation/UseaspRangeValidatortocheckthevaluerangeinanasptextbox.htm
[4] http://www.informit.com/articles/article.aspx?p=101137&seqNum=5
[5] https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.rangevalidator.minimumvalue?view=netframework-4.8
[6] https://www.tutorialspoint.com/asp.net/asp.net_validators.htm
Here is an example of one of the FormViews that I am trying to validate. In the RangeValidator I just have hard coded Max and Min values but I eventually want to have the Min value to be the same value that is in the begin date text box plus day:
<asp:FormView ID="fvNotification" runat="server" Visible="False" DefaultMode="Insert" GridLines="Both" DataSourceID="SqlUserDetails">
<InsertItemTemplate>
<asp:Table ID="Table1" runat="server">
<asp:TableHeaderRow>
<asp:TableHeaderCell>Notification</asp:TableHeaderCell>
<asp:TableHeaderCell>Filter 1</asp:TableHeaderCell>
<asp:TableHeaderCell>Filter 2</asp:TableHeaderCell>
<asp:TableHeaderCell>Begin Date</asp:TableHeaderCell>
<asp:TableHeaderCell>End Date</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow>
<asp:TableCell>
<asp:DropDownList ID="ddNotification" runat="server" DataSourceID="SqlNotifications" DataTextField="Name" DataValueField="Name" ></asp:DropDownList></asp:TableCell>
<asp:TableCell>
<asp:DropDownList ID="ddFilterInsrt" runat="server" DataSourceID="SqlFilters1" DataTextField="Filter" DataValueField="Filter" ></asp:DropDownList></asp:TableCell>
<asp:TableCell>
<asp:DropDownList ID="ddFilterInsrt2 runat="server" >
<asp:ListItem>*</asp:ListItem>
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>B</asp:ListItem>
<asp:ListItem>C</asp:ListItem>
<asp:ListItem>D</asp:ListItem>
</asp:DropDownList>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="TextBoxDateBgnInsrt" runat="server" autocomplete="Disabled" ></asp:TextBox>
<ajaxToolkit:CalendarExtender runat="server" BehaviorID="TextBoxDateBgnInsrt_CalendarExtender" TargetControlID="TextBoxDateBgnInsrt" ID="TextBoxDateBgnInsrt_CalendarExtender"></ajaxToolkit:CalendarExtender>
</asp:TableCell>
<asp:TableCell>
<asp:TextBox ID="TextBoxDateEndInsrt" runat="server" autocomplete="Disabled" ></asp:TextBox>
<ajaxToolkit:CalendarExtender runat="server" BehaviorID="TextBoxDateEndInsrt_CalendarExtender" TargetControlID="TextBoxDateEndInsrt" ID="TextBoxDateEndInsrt_CalendarExtender"></ajaxToolkit:CalendarExtender>
<asp:RangeValidator runat="server" id="rngDate" controltovalidate="TextBoxDateEndInsrt" type="Date" MaximumValue='09/20/2011' MinimumValue="09/01/2011" errormessage="Please enter a valid date within 2006!" display="Dynamic"/>
</asp:TableCell>
</asp:TableRow>
</asp:Table>
<asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" CausesValidation="True" />
<asp:Button ID="InsertCancelButton" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" OnClick="InsertCancelButton_Click1" />
<asp:Button ID="InsertClearEndDateButton" runat="server" Text="Clear End Date" OnClick="InsertClearEndDateButton_Click"/>
</InsertItemTemplate>
</asp:FormView>
I am expecting the FormView to be visible and validate after clicking the button that make the FormView visible but instead I am getting a 500 error.
I'm wanting to change some code which was written for me. I would like to omit displaying the hyperlink where tblResults.videoLink=''
The hyperlink is displayed in the table as "Video Link" so people can click on it. I only want the words/hyperlink "Video Link" to appear in the row where people have entered one.
The code is Microsoft SQL but is written in the ASPX file. The back end is VB but there's VB is pretty much empty.. The ASPX file handles everything...
<h1>Recent Results</h1>
<asp:Panel ID="pnlMyWishes" runat="server">
<asp:SqlDataSource ID="DSWishes" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnectionString %>" SelectCommand="SELECT TOP (100) PERCENT tblResults.wishID, tblResults.Player1AccountID, tblResults.Player2AccountID, tblResults.Player1Result, tblResults.Player2Result, tblResults.venue, tblResults.potSize, tblResults.player1Name, tblResults.player2Name, tblResults.videoLink, tblResults.date FROM tblResults ORDER BY tblResults.date DESC">
</asp:SqlDataSource>
<asp:GridView ID="gdvWishes" width="100%" runat="server" AllowPaging="True" AutoGenerateColumns="False" CssClass="mGrid" DataKeyNames="wishID" DataSourceID="DSWishes" PageSize="20" AllowSorting="True">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:BoundField DataField="player1Name" HeaderText="Player 1" />
<asp:TemplateField HeaderText="Result">
<ItemTemplate>
<asp:Label ID="lblP1" Text='<%# Eval("player1Result").ToString %>' runat="server" Visible="true">
</asp:Label><asp:Label ID="lblVs" Text=" - " runat="server" Visible="true"></asp:Label>
<asp:Label ID="lblP2" Text='<%# Eval("player2Result").ToString %>' runat="server" Visible="true"></asp:Label>
</ItemTemplate>
<ItemStyle Width="17%" />
</asp:TemplateField>
<asp:BoundField DataField="player2Name" HeaderText="Player 2" />
<asp:BoundField DataField="potSize" HeaderText="Pot" />
<asp:BoundField DataField="venue" HeaderText="Venue" />
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:HyperLink ID="hypVideoLink" runat="server" NavigateUrl='<%# Eval("videoLink").ToString %>'>Video Link</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</asp:Panel>
Create a sub like below, call it after the code that fills your GridView with data.
Private Sub HideBlankURLs()
For Each r As GridViewRow in gdvWishes.Rows
If r.RowType = DataControlRowType.DataRow Then //Execute the code only for datarow, excluding footer and header
Dim hypURL As HyperLink
hypURL = r.Cells(5).FindControl("hypVideoLink") //Goes to the column of VideoURL, index 5 is counting from 0 to 5
If hypURL.NavigateURL = "" Then //Checks if the URL is blank, if it is then hide the hyperlink control
hypURL.Visible = False
End If
End If
Next r
End Sub
This will loop through all the rows and look for the control in that column, check if navigate URL is blank, then hide that control.
NOTE: Replace the (//) with single quote (') because SO reads it as text enclosing character rather than a comment.
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
I'm trying to have a label in the edititemtemplate of my gridview show the current date and time when the user clicks the edit linkbutton. When I put date.now in the data binding box, I can see the result I want, but when I click update, I get an error that the field can't be null. It works fine when I try it for the footer row, but not the edit row. Here's the footer row code that works:
'Get Time Recorded
Dim lblFtrTimeRecorded As Label = GridView1.FooterRow.FindControl("lblFtrTimeRecorded")
lblFtrTimeRecorded.Text = Date.Now
Here's the template field .aspx code:
<asp:TemplateField HeaderText="TimeRecorded" SortExpression="TimeRecorded">
<EditItemTemplate>
<asp:Label ID="lblEditTimeRecorded" runat="server"
Text='<%# Bind("TimeRecorded") %>'></asp:Label>
</EditItemTemplate>
<FooterTemplate>
<asp:Label ID="lblFtrTimeRecorded" runat="server"></asp:Label>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblTimeRecorded" runat="server"
Text='<%# Bind("TimeRecorded") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Any help is greatly appreciated!
Write this code :
Dim lblFtrTimeRecorded As Label = GridView1.Rows[GridView1.EditIndex].FindControl("lblFtrTimeRecorded")
lblFtrTimeRecorded.Text = Date.Now
I have a gridview with 2 columns.
First field contains checkbox named chkSelect and second column is a label which is binded with EmailId.
<asp:GridView ID="gvwNewsLetter" runat="server" AutoGenerateColumns="false" DataKeyNames="UserID">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelectMail" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="EmailID">
<ItemTemplate>
<asp:Label ID="lblEmail" runat="server" Text='<%#Eval("EmailID")%>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
When I check each checkbox I have to display mailid in corresponding row in a textarea which is outside gridview like" abc#gmail.com,sdf#gmail.com". If I uncheck inbetween I have to remove that particular id from textbox. Can anybody help give the code to remove mailid on unchecking the checkbox.
Can you not just rebuild the entire string each time a checkbox is checked/unchecked? Might be faster than trying to parse through and modify the existing string each time.