RangeValidation Throws error - html

I am using a range validation in asp for a date range...
<EditItemTemplate>
<asp:RequiredFieldValidator ID="RequiredFieldValidatordtmStartDateEdit" runat="server" ErrorMessage="Start Date is required" ControlToValidate="dtmStartDateEdit"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="RangeValidatordtmStartDateEdit" runat="server" Type="String" ErrorMessage="Range is +/- 1 year" ControlToValidate="dtmStartDateEdit" MaximumValue="DATETIME.Today.ADDYEARS(1).ToShortDateString()" MinimumValue="DATETIME.Today.ADDYEARS(-1).ToShortDateString()"></asp:RangeValidator>
<ajaxToolkit:CalendarExtender ID="CalendarExtenderStartDateEdit" runat="server" TargetControlID="dtmStartDateEdit"></ajaxToolkit:CalendarExtender>
<asp:TextBox ID="dtmStartDateEdit" runat="server">
</asp:TextBox>
</EditItemTemplate>
The error I get is that the Maximum cannot be smaller than the minimum.

Add type attribute , and I wonder ToShortDateString() returns String or use Type = Date if not.
<asp:RangeValidator ID="RangeValidatordtmCloseDateAdd" runat="server"
ErrorMessage="Range is +/- 1 year" ControlToValidate="dtmCloseDateAdd"
MaximumValue="DATETIME.Today.ADDYEARS(1).ToShortDateString()"
MinimumValue="DATETIME.Today.ADDYEARS(-1).ToShortDateString()"
Type = "String">
</asp:RangeValidator>

What I did was extract the Max and Min statements and placed them in the PageLoad event for each RangeValidator. It works fine.

Related

ASP.NET/HTML - How would I update an SQLDataSource with a <select><option>?

I have an ASP.NET HTML website in which I want to update my SQLDataSource SELECT command using a drop-down menu. The user can select to sort by Date, Duration or Player, and the GridView will update showing the new, sorted results from my mdf database. I'm really not sure at all how to approach this as I am fairly new to ASP.NET. I could just do with some pointers on how to go about it, and what method to use. I can google tutorials, the problem is knowing what to google. Any advice greatly appreciated :)
My code:
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="RunsData">
<Columns>
<asp:BoundField DataField="PlayerId" HeaderText="PlayerId" SortExpression="PlayerId" />
<asp:BoundField DataField="Duration" HeaderText="Duration" SortExpression="Duration" />
<asp:BoundField DataField="VersionId" HeaderText="VersionId" SortExpression="VersionId" />
<asp:BoundField DataField="DateUploaded" HeaderText="DateUploaded" SortExpression="DateUploaded" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="RunsData" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [PlayerId], [Duration], [VersionId], [DateUploaded] FROM [Run] ORDER BY [Duration]"></asp:SqlDataSource>
</form>
<div>
<label class="label" for="version">Version: </label>
<select name="version" id="version">
<option value="lev1">Level 1</option>
<option value="lev1to3">Level 1-3</option>
<option value="lev8">Level 8</option>
<option value="lev17">Level 17</option>
</select>
<label class="label" for="sortby">Sort By: </label>
<select name="sortby" id="sortby">
<option value="duration">Duration</option>
<option value="date">Date</option>
<option value="player">Player</option>
</select>
</div>
</div>
Ok, first up, I would think it is better to have the filters at the top (above) the grid, and not below? (just a idea).
and in fact, even better idea would be to drop in the two combo boxes RIGHT into the grid heading - even better!!!
but, lets take this one step at a time.
First up, I recommend we dump (remove) the data source in the web page. The can be handy, wizards generate them - thank you much - all good. However, EVEN when I often use a wizard to create the GV, I THEN blow out the data source, and use code. And when is a GOOD idea to use code to fill the GV?
Why of course when you want to filter it!!!
So, lets do this:
Delete/remove the Sqldata source - we not going to use it.
Remove this from GV - DataSourceID="RunsData"
Also, you clear used the wizards to create and setup that GV, but then now use select html? Why not use DropDown lists? The wizards not only can build them for you (like the GV, they also have a rich .net event model. And you can shove, drive the dropdown list just like the GV (they are data source friendly).
So, we going to assume this markup now:
<div style="float:left">
<label class="label" for="version">Version: </label>
<asp:DropDownList ID="cboVersion" runat="server" Width="150px">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="1">Level 1</asp:ListItem>
<asp:ListItem Value="1-3">Level 1-3</asp:ListItem>
<asp:ListItem Value="8">Level 8</asp:ListItem>
<asp:ListItem Value="17">Level 17</asp:ListItem>
</asp:DropDownList>
</div>
<div style="float:left;padding-left:25px">
<label class="label" for="sortby">Sort By:</label>
<asp:DropDownList ID="cboSortBy" runat="server" Width="150px">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="duration">Duration</asp:ListItem>
<asp:ListItem Value="DateUploaded">Date</asp:ListItem>
<asp:ListItem>Player</asp:ListItem>
</asp:DropDownList>
</div>
<div style="clear:both;height:10px"></div> <%-- Start new line for grid --%>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="RunsData">
<Columns>
<asp:BoundField DataField="PlayerId" HeaderText="PlayerId" />
<asp:BoundField DataField="Duration" HeaderText="Duration" />
<asp:BoundField DataField="VersionId" HeaderText="VersionId" />
<asp:BoundField DataField="DateUploaded" HeaderText="DateUploaded" />
</Columns>
</asp:GridView>
</form>
So, note that just like GV the dropdown list as a edit items option, like this:
And then you get this:
Also, when you want level say 1-3 is that column a number type?
And as noted, I put the filters tat the top of the grid. Since your placing the filers below the grid? You have to explain that goal - not seen filters on the bottom of a grid in about 20 years now - maybe some desktop apps? But SUPER rare. Since that choice is SUPER RARE? Then you may well have a good reason, but I placed the filter at the top. In fact, we would/could consider placing the dropdowns in the header of the GV (and that is allowed!!!). But, hey, one step at a time.
I also don't grasp, see the need for two forms on the page? (again, might be a reason, but you better have one heck of a good and great reason for that choice).
So, we now have this:
<div style="float:left">
<label class="label" for="version">Version: </label>
<asp:DropDownList ID="cboVersion" runat="server" Width="150px" AutoPostBack="true">
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="1">Level 1</asp:ListItem>
<asp:ListItem Value="1,3">Level 1-3</asp:ListItem>
<asp:ListItem Value="8">Level 8</asp:ListItem>
<asp:ListItem Value="17">Level 17</asp:ListItem>
</asp:DropDownList>
</div>
<div style="float:left;padding-left:25px">
<label class="label" for="sortby">Sort By:</label>
<asp:DropDownList ID="cboSortBy" runat="server" Width="150px" AutoPostBack="true" >
<asp:ListItem></asp:ListItem>
<asp:ListItem Value="duration">Duration</asp:ListItem>
<asp:ListItem Value="DateUploaded">Date</asp:ListItem>
<asp:ListItem>Player</asp:ListItem>
</asp:DropDownList>
</div>
<div style="clear:both;height:10px"></div> <%-- Start new line for grid --%>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
Width="30%" CssClass="table">
<Columns>
<asp:BoundField DataField="PlayerId" HeaderText="PlayerId" />
<asp:BoundField DataField="Duration" HeaderText="Duration" />
<asp:BoundField DataField="VersionId" HeaderText="VersionId" />
<asp:BoundField DataField="DateUploaded" HeaderText="DateUploaded" />
</Columns>
</asp:GridView>
Note careful we added/allow/have a BLANK choice for the two combo boxes.
Ok, so now our code to load up the grid like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
loadgrid()
End If
End Sub
Sub loadgrid()
Using conn As New SqlConnection(My.Settings.TEST4)
Using cmdSQL As New SqlCommand("SELECT PlayerId, Duration, VersionId, DateUploaded FROM [Run]", conn)
' add filter
Dim strWhere As String = ""
If cboVersion.Text <> "" Then
If InStr(cboVersion.SelectedItem.Value, "-") = 0 Then
' one value
cmdSQL.CommandText &= " WHERE VersionID = #id"
cmdSQL.Parameters.Add("#id", SqlDbType.Int).Value = cboVersion.SelectedItem.Value
Else
' we have range
Dim MyRnage() As String = Split(cboVersion.SelectedItem.Value, "-")
cmdSQL.CommandText &= " WHERE VersionID is between #lower and #upper"
cmdSQL.Parameters.Add("#lower", SqlDbType.Int).Value = MyRnage(0)
cmdSQL.Parameters.Add("#upper", SqlDbType.Int).Value = MyRnage(1)
End If
End If
' add order by
If cboSortBy.Text = "" Then
cmdSQL.CommandText &= " ORDER BY Duration"
Else
cmdSQL.CommandText &= " ORDER BY " & cboSortBy.SelectedItem.Value
End If
Dim rstData As New DataTable
conn.Open
rstData.Load(cmdSQL.ExecuteReader)
GridView1.DataSource = rstData
GridView1.DataBind()
End Using
End Using
End Sub
Since we have auto post-back, then for both the sort by combo, filter by, then we have two event stubs here.
Protected Sub cboVersion_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboVersion.SelectedIndexChanged
loadgrid()
End Sub
Protected Sub cboSortBy_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboSortBy.SelectedIndexChanged
loadgrid()
End Sub
Edit:
The follow up question was where did TEST4 come from? Why of course it is my own setting.
From VS menu, project->"my project"->settings.
There we go to settings, and then do this:
So then in above hit the [...] and you get the connection string builder.
I mean, you can manually edit web config, but that's kind of human torture, and using the above settings is oh so much easy. So for application settings, you can use the above to create settings for your application. Say company name, or connection strings, or whatever. Those settings are placed in web.config for you. So, you not limited to just connection strings, but all kinds of constants settings such as company name, maybe company address etc.

Datetime error using datefield

I'm using ext.net 3 and i need to create datetime together but in this ext both time and date are not same.
<ext:DateField runat="server" ID="date1" MarginSpec="0 10 0 20" LabelAlign="Right" Format="yyyy-MM-dd h:i:s" FieldLabel="Gate In Date/Time" AllowBlank="false" IndicatorText="*" IndicatorCls="red-text"></ext:DateField>
The result is 2016-06-01 12:00:00
The date works fine but the time got some problem.
You are returning data from the DateField so the time is going to always be 12:00:00. Ext.Net includes a TimeField as well. It's a dropdown list of formatted times. Use both to have your user select Date & Time.
<ext:FieldContainer runat="server" FieldLabel="Pick Date & Time" Layout="HBoxLayout">
<Items>
<ext:DateField ID="DateField1" runat="server">
</ext:DateField>
<ext:ToolbarSeparator Width="5" />
<ext:TimeField ID="Timefield1" runat="server" Width="100">
</ext:TimeField>
</Items>
</ext:FieldContainer>

How to set current date in CalendarExtender

Requirement is simple.
How to set current date in CalendarExtender control.
<cal:CalendarExtender ID="calDate" runat="server" SelectedDate="2008-01-01" TargetControlID="txtDate" CssClass="CalendarExtender" Format="yyyy/MM/dd">
Here the selected date is 2008-01-01. I need to show current date instead of 2008-01-01
Appreciate your assistance
You just need to assign it in codebehind, for example in Page_Load:
if(!IsPostBack)
calDate.SelectedDate = DateTime.Today;
Another example using #Hutchonoid approach: example below illustrate how to correctly use ajaxcontrolTookKit CalendarExtender.
<ajaxControlToolKit:CalendarExtender runat="server"
id="cal1"
TargetControlID="txtDateFrom"
CssClass="MyCalendar ajax__calendar ajax__calendar_hover"
Format="dd/MM/yyyy"
PopupButtonID="imgControl"
PopupPosition="BottomRight"
SelectedDate="<%# DateTime.Today %>" >
</ajaxControlToolKit:CalendarExtender>
<asp:TextBox Type="text" ID="txtDateFrom" runat="server"></asp:TextBox>
<asp:ImageButton ID="imgControl" runat ="server" ImageUrl
="~/_icons/ajaxcalendar.png" />
Hope the above code snip-it helps or at least clarify the concept.

Could not find control 'ControlID' in ControlParameter 'ParamName'

Ok guys, I know this question has been asked a million times. I've searched for days and none of the online solutions found actually work for me. Here's my code:
<asp:SqlDataSource
ID="SqlDataSource2"
runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>"
SelectCommand="SELECT VTPNAME, NETWORKKEY, FKVTPDOMAIN, VLANNUMBER, NETDESCRIPTION, BEGINNINGIP,
HOSTS, DEFAULTGATEWAY FROM NETWORK.NETWORK, NETWORK.VTPDOMAIN WHERE
NETWORK.FKVTPDOMAIN = VTPDOMAIN.VTPDOMAINKEY"
DeleteCommand="DELETE FROM NETWORK.NETWORK WHERE NETWORKKEY =: NETWORKKEY"
UpdateCommand="UPDATE NETWORK.NETWORK SET FKVTPDOMAIN =:updateFKVTP, VLANNUMBER = :VLANNUMBER,
NETDESCRIPTION = :NETDESCRIPTION,BEGINNINGIP = :BEGINNINGIP,
HOSTS = :HOSTS,DEFAULTGATEWAY = :DEFAULTGATEWAY WHERE NETWORKKEY = :NETWORKKEY"
InsertCommand="INSERT INTO NETWORK.NETWORK (VLANNUMBER,NETDESCRIPTION,BEGINNINGIP,HOSTS,DEFAULTGATEWAY,FKVTPDOMAIN) VALUES (:vlanNet,:descNet,:begIpNet,:hostNet,:defNet,:vtpdomainkey)">
<InsertParameters>
<asp:ControlParameter Name="vlanNet" ControlID="vlanTextbox" />
<asp:ControlParameter Name="descNet" ControlID="descTextbox" />
<asp:ControlParameter Name="begIpNet" ControlID="beginIPTextbox" />
<asp:ControlParameter Name="hostNet" ControlID="hostsTextbox" />
<asp:ControlParameter Name="defNet" ControlID="defaultGatTextBox" />
<asp:ControlParameter Name="vtpdomainkey" ControlID="vtpDomainFKDropDown" />
</InsertParameters>
<UpdateParameters>
<asp:ControlParameter Name="updateFKVTP" ControlID="vtpNameDropDownUpdate" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:GridView
ID="GridView2"
runat="server"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource2"
AllowPaging="True"
AllowSorting="True"
DataKeyNames="NETWORKKEY"
Width="650px"
OnRowUpdating="GridView2_RowUpdating">
<Columns>
<asp:CommandField HeaderText="Options" ShowDeleteButton="True" ShowEditButton="True" />
<asp:TemplateField HeaderText="VTP Domain" SortExpression="VTPNAME">
<EditItemTemplate>
<asp:DropDownList ID="vtpNameDropDownUpdate" runat="server" DataSourceID="SqlDataSource6" DataTextField="VTPNAME" DataValueField="VTPDOMAINKEY">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("VTPNAME") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Here's the actual error given:
Could not find control 'vtpNameDropDownUpdate' in ControlParameter 'updateFKVTP'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Could not find control 'vtpNameDropDownUpdate' in ControlParameter 'updateFKVTP'.
Everything works as is supposed to, except the dropDownList. It will NOT find it, I have tried dollar signs, colons,underscore, you name it, to tell it where the control is and no result. They are in the same and they both lay one under the other, just as I posted it here. I got the first row to actually update because I tried the method where you right click on the dropdownlist while running and you "inspect the element" and copy and paste the whole ControlID string into the ControlParameter ControlID. The problem is, there are several rows, so it will only work for the one element I inspected and not all the other ones. Any help would be appreciated and thank you in advance for your time!
-Fernando
The DropDownList is inside The Template Control, so you should find the template control first.In this example template control is in 7th column of Gridview. after find template inside that you can find DropDownList :
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
var index = e.RowIndex;
var dropDownctr= GridView1.Rows[index].Controls[6].FindControl("vtpNameDropDownUpdate")
}

Comparing date with exceptional date in asp.net Validator

I am using compare validator of asp.net to compare the Date, I am comparing input date with today's date for that I have written code as below.
<asp:CompareValidator ID="StartDateCompareVal" ValidationGroup="vgStep4" runat="server"
ControlToValidate="txtDueDate" Display="Dynamic" ErrorMessage="Dateshould be greater than today's date."
Operator="GreaterThan" ValueToCompare="<%# DateTime.Today.ToShortDateString() %>"
Type="Date"></asp:CompareValidator>
It is working fine, but Now my requirement is that if someone enters date as 00/00/0000 so, No need to compare the value and should be accepted
Looks like you might want to use a CustomValidator instead of the CompareValidator.
.aspx page:
<form id="frmAspnet" runat="server">
<asp:ValidationSummary runat="server" ID="vSummary" />
<div>
<label>
Enter Date Greater Than Today:
<asp:TextBox runat="server" ID="txtDate" />
</label>
</div>
<div>
<asp:Button runat="server" ID="cmdSubmit" Text="Submit" />
</div>
</form>
code behind:
private void cmdSubmit_Click(object sender, EventArgs e)
{
String validationGroup = "vgStep4";
vSummary.ValidationGroup = validationGroup;
Page.Validate(validationGroup);
DateTime dateEntered = DateTime.TryParse(txtDate.Text, out dateEntered) ? dateEntered : DateTime.MinValue;
Page.Validators.Add(new CustomValidator()
{
IsValid = (dateEntered > DateTime.Now.Date) || (txtDate.Text == "00/00/0000"),
ValidationGroup = validationGroup,
ErrorMessage = "Date should be greater than today's date."
});
if (Page.IsValid)
{
// Date entered is valid!
// or 00/00/0000 was entered
}
}