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.
Related
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.
I have check.aspx file which has:
<%# MasterType VirtualPath="~/MSW.master" %>
And in this master file I have:
<%# Register Src="UserControls/Common/StatusBar.ascx" TagName="StatusBar" TagPrefix="uc3" %>
And in this StatusBar.ascx, I have a div:
<div id="status_box_content">
<asp:Label ID="lblWelcome" runat="server" Text="Welcome " ></asp:Label>
<asp:Label ID="lbUser" runat="server"meta:resourcekey="lblFullNameResource1"></asp:Label>
<asp:Label ID="lblPartnerInfo" runat="server" ></asp:Label>
<asp:HyperLink Font-Underline="False" NavigateUrl="~/profile/Logout.aspx"
ID="HLinkLogout" runat="server" meta:resourcekey="HLinkLogoutResource1">Logout</asp:HyperLink>
</div>
I want this div with id ="status_box_content" to be invisible in check.aspx file. But everything else from master file is needed.
How do I make the div invisible while keeping the master file?
In your check.aspx, hide the div using jquery. It works perfectly fine. I was making a huge mistake while calling it.So yeah,it works! :)
Notes: Make your div runat="server"
Aspx Page
<div id="status_box_content" runat="server">
<asp:Label ID="lblWelcome" runat="server" Text="Welcome " ></asp:Label> <asp:Label ID="lbUser" runat="server"meta:resourcekey="lblFullNameResource1"></asp:Label>
<asp:Label ID="lblPartnerInfo" runat="server" ></asp:Label>
<asp:HyperLink Font-Underline="False" NavigateUrl="~/profile/Logout.aspx"
ID="HLinkLogout" runat="server" meta:resourcekey="HLinkLogoutResource1">Logout</asp:HyperLink>
</div>
Code Behind Page : Put This Code in your content page_load event
HtmlGenericControl DivCount = (HtmlGenericControl)Page.Master.FindControl("status_box_content");
DivCount.Visible = false;
Make runat= server to your div.
And then on page load of check.aspx use make that div invisible:
this.Master.findcontrol("divname").visible= false;
As the div is inside UserControl and User Control is inside Master Page, just try to access UserControl First in your page, then find out div and make it invisible. You could try out this:
First make the div as server control,Add runat="server" in div :
<div id="status_box_content" runat="server">
UserControl uc = ((UserControl)this.Master.FindControl("ucTopUser"));
HtmlGenericControl div = (HtmlGenericControl )uc.FindControl("status_box_content");
div.Visible = false;
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")
}
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.
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
}
}