Как использовать ASP.NET 4.0 время выбора пользователя, используя C# ?
Привет,
Я новичок в концепции выбора времени в asp.net,во время поиска я получил следующую ссылку.
ASP.NET 4.0 элемента управления datepicker контроля пользователей [^]
Эта ссылка работает точно так же, как я хочу.Когда я загружаю проект, он работает хорошо.
Но проблема в том, что разработано с использованием vb.net язык, тот же код, который я хочу на языке C#.
Пожалуйста, помогите мне.
Что я уже пробовал:
Здесь я добавил веб-пользовательский контроль в свой проект, т. е.
WebUserControl1.ascx.
это мой код страницы WebUserControl1.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="TimePickerDemo1.CustomControls.WebUserControl1" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> <link href="TimeExtender.css" rel="stylesheet" type="text/css" /> <asp:ImageButton ID="ibtnShowPicker" runat="server" ImageUrl="btnTimeExtenderBlue.gif" OnClientClick="return false;" CssClass="btnTimeExtender_Style" /> <div> <asp:PopupControlExtender ID="PopupControlExtender_Time" PopupControlID="datalistTimes" CommitProperty="value" Position="Bottom" runat="server"> </asp:PopupControlExtender> <asp:DataList ID="datalistTimes" RepeatDirection="Horizontal" RepeatColumns="4" OnItemDataBound="datalistTimes_OnItemDataBound" CssClass="Datalist_ControlStyle" HeaderStyle-CssClass="Datalist_HeaderStyle" ItemStyle-CssClass="Datalist_ItemStyle" runat="server" > <HeaderTemplate> <div class="Datalist_HeaderLeft"> </div> <div class="Datalist_HeaderCenter"> <asp:LinkButton ID="lbtnHeaderTime" OnCommand="lbtnHeaderTime_OnCommand" ToolTip="click to select current time" runat="server" /> </div> <div class="Datalist_HeaderRight"> <asp:LinkButton ID="lbtnHeaderAM" Text="AM" OnCommand="lbtnHeaderAM_OnCommand" CommandArgument="am" runat="server" /> <asp:LinkButton ID="lbtnHeaderPM" Text="PM" OnCommand="lbtnHeaderPM_OnCommand" CommandArgument="pm" runat="server" /> </div> </HeaderTemplate> <ItemTemplate> <asp:LinkButton ID="lbtnTime" CommandName="second" OnCommand="lbtnTime_Onclick" CommandArgument='<%# Eval("Time") %>' Text='<%# Eval("Time") %>' runat="server"/> </ItemTemplate> </asp:DataList> </div>
И это код за кодом страницы
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Text.RegularExpressions; using System.Data; using System.Collections; using System.Globalization; namespace TimePickerDemo1.CustomControls { public partial class WebUserControl1 : System.Web.UI.UserControl { protected void Page_Init(object sender, System.EventArgs e) { // set property defaults based on selected properties to fix conflicts FixPropertyConflicts(); // validate selected date ValidateSelectedTime(); // load times BindDataSource(); // show or hide the picker button that appears beside parent control ShowOrHideTimePickerButton(); } private void ShowOrHideTimePickerButton() { bool bolShowButton = System.Convert.ToBoolean(ViewState["ShowButton"]); if (bolShowButton) { this.ibtnShowPicker.Visible = true; this.PopupControlExtender_Time.TargetControlID = this.ibtnShowPicker.UniqueID; // set popup position this.PopupControlExtender_Time.OffsetX = (7 + GetParentControlWidth()) * (-1); } else { this.ibtnShowPicker.Visible = false; // must set new target control this.PopupControlExtender_Time.TargetControlID = System.Convert.ToString(ViewState["TargetControlID"]); } } private int GetParentControlWidth() { string strTargetControlID = System.Convert.ToString(ViewState["TargetControlID"]); Control objParentControl = (Control)this.Parent.FindControl(strTargetControlID); if (objParentControl == null) return 50; string strControlType = objParentControl.GetType().ToString(); int i = 0; if (strControlType.ToLower().Contains("textbox")) { i = 1; } else { i = 2; } switch (i) { case 1: { TextBox textboxParent = (TextBox)objParentControl; return System.Convert.ToInt32(textboxParent.Width.Value); } case 2: { Label lblParent = (Label)objParentControl; return System.Convert.ToInt32(lblParent.Width.Value); } } return 50; } private void BindDataSource() { // datalistTimes. this.datalistTimes.DataSource = CreateDataSource(); this.datalistTimes.DataBind(); } private ICollection CreateDataSource() { // Create time data for the DataList control. DataTable dt = new DataTable(); DataRow dr; // Define the columns of the table. dt.Columns.Add(new DataColumn("Time", typeof(string))); // Populate the table with sample values. int intMinuteIncrement = Convert.ToInt32(ViewState["MinuteIncrement"]); if (intMinuteIncrement == 0) intMinuteIncrement = 30; // 24 hour clock or 12 hour clock int intMaxTime = 720 - intMinuteIncrement; string strAMorPM = " " + SelectAMorPM(); // show am and pm if (System.Convert.ToBoolean(ViewState["ShowAMandPM"])) { intMaxTime = 1440 - 1; // don't show last time strAMorPM = " am"; } // show 24 hour clock string strColon = ":"; string strHoursFormat = "{0:#0}"; if (System.Convert.ToBoolean(ViewState["Show24HourClock"])) { intMaxTime = 1440 - 1; // don't show last time strAMorPM = ""; strHoursFormat = "{0:00}"; if (!System.Convert.ToBoolean(ViewState["Show24HourClockColon"])) strColon = ""; } else if (System.Convert.ToBoolean(ViewState["ShowLeadingZeros"])) strHoursFormat = "{0:00}"; // populate times int intHours = 0; int intMins = 0; for (int intTime = 0; intTime <= intMaxTime; intTime += intMinuteIncrement) { if (intTime == 0 | intTime % 60 == 0) { // reset mins intMins = 0; // add hours if (System.Convert.ToBoolean(ViewState["Show24HourClock"])) // 24 hour clock intHours = intTime / 60; else { // 12 hour clock intHours = intTime / 60; if (System.Convert.ToBoolean(ViewState["ShowAMandPM"]) & intHours > 11) { strAMorPM = " pm"; if (intHours > 12) intHours = intHours - 12; } if (intHours == 0) intHours = 12; } // add row string timeHours = string.Format(strHoursFormat + strColon + "{1:00}", intHours, 0) + strAMorPM; dr = dt.NewRow(); dr[0] = timeHours; dt.Rows.Add(dr); } else { // add minutes intMins += intMinuteIncrement; string timeMinutes = string.Format(strHoursFormat + strColon + "{1:00}", intHours, intMins) + strAMorPM; dr = dt.NewRow(); dr[0] = timeMinutes; dt.Rows.Add(dr); } } // return dataview DataView dv = new DataView(dt); return dv; } protected void Page_Load(object sender, EventArgs e) { // PopupControlExtender_Time } private void FixPropertyConflicts() { // set defaults if (ViewState["ShowButton"] == null) ViewState["ShowButton"] = "false"; if (ViewState["SelectedTime"] == null) ViewState["SelectedTime"] = ""; if (ViewState["Show24HourClock"] == null) ViewState["Show24HourClock"] = "false"; if (ViewState["ShowLeadingZeros"] == null) ViewState["ShowLeadingZeros"] = "false"; if (ViewState["MinuteIncrement"] == null) ViewState["MinuteIncrement"] = "30"; if (ViewState["Show24HourClockColon"] == null) ViewState["Show24HourClockColon"] = "false"; // fix 24 hour clock conflicts if (System.Convert.ToBoolean(ViewState["Show24HourClock"])) { ViewState["ShowAMandPM"] = "false"; ViewState["ShowLeadingZeros"] = "true"; } // fix 12 hour clock conflicts and set defaults if (!System.Convert.ToBoolean(ViewState["Show24HourClock"])) { ViewState["Show24HourClockColon"] = "false"; if (ViewState["ShowAMandPM"] == null) ViewState["ShowAMandPM"] = "true"; } // Increment must be 5,10,15... int intIncrement = System.Convert.ToInt32(ViewState["MinuteIncrement"]); if (intIncrement > 60) ViewState["MinuteIncrement"] = "60"; if (intIncrement < 5) ViewState["MinuteIncrement"] = "30"; if (intIncrement % 5 > 0) ViewState["MinuteIncrement"] = "30"; } protected void datalistTimes_OnItemDataBound(object sender, DataListItemEventArgs e) { // header if (e.Item.ItemType == ListItemType.Header) { LinkButton objlblTime = (LinkButton)e.Item.FindControl("lbtnHeaderTime"); if (objlblTime != null) { string strCurrTime = DateTime.Now.ToShortTimeString(); if (System.Convert.ToBoolean(ViewState["Show24HourClock"])) strCurrTime = Format24HourTime(strCurrTime); objlblTime.Text = SetLeadingZero(strCurrTime); objlblTime.BorderWidth = 0; // could not get working in CSS so do it here } // set AM button LinkButton objlbtnHeader = (LinkButton)e.Item.FindControl("lbtnHeaderAM"); if (objlbtnHeader != null) { if (System.Convert.ToBoolean(ViewState["Show24HourClock"])) HideAMorPMButton(objlbtnHeader); else // show both buttons and select one SetButtonsAMorPM(objlbtnHeader, "am"); } // set PM buton objlbtnHeader = (LinkButton)e.Item.FindControl("lbtnHeaderPM"); if (objlbtnHeader != null) { if (System.Convert.ToBoolean(ViewState["Show24HourClock"])) // hide buttons if displaying 24 hour clock HideAMorPMButton(objlbtnHeader); else // show both buttons and select one SetButtonsAMorPM(objlbtnHeader, "pm"); } } // can set selected time here - not used // need routine to check which time is closest to interval time if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem) { LinkButton objlbtnItem = (LinkButton)e.Item.FindControl("lbtnTime"); if (objlbtnItem != null) { if (Format24HourTime(objlbtnItem.Text) == Format24HourTime(System.Convert.ToString(this.ViewState["SelectedTime"]))) { } else { } } } } protected void lbtnHeaderTime_OnCommand(object sender, CommandEventArgs e) { // set to current time string strCurrTime = DateTime.Now.ToShortTimeString(); if (System.Convert.ToBoolean(this.ViewState["Show24HourClock"])) strCurrTime = Format24HourTime(strCurrTime); // hide the popup and return the time CommitTime(strCurrTime); } private void CommitTime(string strSelectedTime) { if (System.Convert.ToBoolean(this.ViewState["ShowButton"])) SetParentControlValue(strSelectedTime); this.PopupControlExtender_Time.Commit(strSelectedTime); } protected void lbtnHeaderAM_OnCommand(object sender, CommandEventArgs e) { this.ViewState["SelectedTimeAMorPM"] = "am"; LinkButton myButton = sender as LinkButton; SetButtonsAMorPM(myButton, "am"); // must set Selected time to am to refresh datasource this.ViewState["SelectedTime"] = GetTimePart() + " am"; BindDataSource(); } protected void lbtnHeaderPM_OnCommand(object sender, CommandEventArgs e) { this.ViewState["SelectedTimeAMorPM"] = "pm"; LinkButton btn = sender as LinkButton; SetButtonsAMorPM(btn, "pm"); // must set Selected time to pm to refresh datasoure this.ViewState["SelectedTime"] = GetTimePart() + " pm"; BindDataSource(); } //private void SetButtonsAMorPM(object sender, string p) //{ // throw new NotImplementedException(); //} protected void lbtnTime_Onclick(object sender, CommandEventArgs e) { string strSelectedValue = e.CommandArgument.ToString().ToUpper(); CommitTime(strSelectedValue); } private void SetParentControlValue(string strSelectedValue) { // get parent control string strTargetControlID = System.Convert.ToString(this.ViewState["TargetControlID"]); Control objParentControl = (Control)this.Parent.FindControl(strTargetControlID); // get type of control string strType = objParentControl.GetType().ToString(); int i=0; if(strType.ToLower().Contains("textbox")) { i=1; } else { i=2; } switch (i) { case 1: { TextBox textboxParent = (TextBox)objParentControl; textboxParent.Text = strSelectedValue; break; } case 2: { Label lblParent = (Label)objParentControl; lblParent.Text = strSelectedValue; break; } } } private void SetButtonsAMorPM(LinkButton objlbtnHeader, string strAMorPM) { string strTime = ""; if (System.Convert.ToBoolean(this.ViewState["ShowAMandPM"])) { // hide button if displaying am and pm objlbtnHeader.BorderWidth = 0; objlbtnHeader.Visible = false; } else // show both buttons and select one if (SelectAMorPM(strTime) == strAMorPM) objlbtnHeader.BorderWidth = 1; else objlbtnHeader.BorderWidth = 0; } private void HideAMorPMButton(LinkButton objlbtnHeader) { objlbtnHeader.Visible = false; } private string SetLeadingZero(string strTime) { if (System.Convert.ToBoolean(this.ViewState["Show24HourClock"])) return strTime; if (!System.Convert.ToBoolean(this.ViewState["ShowLeadingZeros"])) { if (strTime.Substring(0, 1) == "0") return " " + strTime.Substring(1); } return strTime; } protected bool CheckDate(String date) { DateTime Temp; if (DateTime.TryParse(date, out Temp) == true) return true; else return false; } private void ValidateSelectedTime() { string strSelectedTime = System.Convert.ToString(ViewState["SelectedTime"]); // first validate the time entered - set to empty string if not valid if (!CheckDate(strSelectedTime)) try { // DateTime dt = DateTime.Parse(strSelectedTime); this.ViewState["SelectedTime"] = ""; //return true; return; } catch { //return false; } // Format time if (System.Convert.ToBoolean(ViewState["Show24HourClock"])) this.ViewState["SelectedTime"] = Format24HourTime(strSelectedTime); else { this.ViewState["SelectedTime"] = Format12HourTime(strSelectedTime); this.ViewState["SelectedTimeAMorPM"] = SelectAMorPM(strSelectedTime); } } private string Format12HourTime(string strTime) { strTime = string.Format("{00:00}", strTime); strTime = Regex.Replace(strTime, "[^1234567890]", ""); if (strTime.Length < 4) strTime = "0" + strTime; // Response.Write(strTime); DateTime DT = DateTime.ParseExact(strTime.ToString(),"HHmm", System.Globalization.CultureInfo.InvariantCulture); string[] formats = new string[] { "hhmm" }; DateTime dt = DateTime.ParseExact(DT.ToString(), formats, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AdjustToUniversal); return dt.ToString("hh:mm tt"); } private string Format24HourTime(string strTime) { string strTimeOnly = GetTimePart(strTime); if (strTime.ToLower().Contains("pm")) { // convert to 24 hour clock int intHours = System.Convert.ToInt32(strTimeOnly.Substring(0, 2)); intHours += 12; strTimeOnly = System.Convert.ToString(intHours).PadLeft(2, '0') + strTimeOnly.Substring(2); } return strTimeOnly; } private string SelectAMorPM(string strTime = "") { string strSelectedTime = System.Convert.ToString(ViewState["SelectedTime"]); if (strTime != "") strSelectedTime = strTime.ToLower(); if (strSelectedTime.ToLower().Contains("am")) return "am"; else return "pm"; } private string GetTimePart(string strTime = "") { string strSelectedTime = System.Convert.ToString(ViewState["SelectedTime"]).ToLower(); if (strTime != "") strSelectedTime = strTime.ToLower(); strSelectedTime = strSelectedTime.Replace("am", "").Trim(); strSelectedTime = strSelectedTime.Replace("pm", "").Trim(); int intLength = 5; if (System.Convert.ToBoolean(ViewState["Show24HourClock"]) & !System.Convert.ToBoolean(ViewState["Show24HourClockColon"])) { // no colon strSelectedTime = strSelectedTime.Replace(":", ""); intLength = 4; } // pad with leading zeros if (strSelectedTime.Length < intLength) strSelectedTime = "0" + strSelectedTime; return strSelectedTime; } } }
И это моя страница default.aspx
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TimePickerDemo1._Default" %> <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %> <%@ Register Src="CustomControls/WebUserControl1.ascx" TagName="TimeExtender" TagPrefix="cc1" %> <asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent"> <link href="Styles/TimePicker.css" rel="Stylesheet" type="text/css" /> </asp:Content> <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <div class="divMainContainer"> <h3>Test Time Picker Extender</h3> <div class="divSameLine"> <!-- Start Time - Extender using properties --> <asp:Label ID="lblStartTime" Text="Start Time:" AssociatedControlID="txtTime" runat="server" /> <asp:TextBox ID="txtTime" Width="100" runat="server" /> <cc1:TimeExtender ID="TimePicker1" MinuteIncrement="15" TargetControlID="txtTime" ShowButton="false" ShowAMandPM="false" Show24HourClock="false" ShowLeadingZeros="false" runat="server" /> </div> <div class="divSameLine"> <!-- End Time - Extender with defaults showing am and pm times --> <asp:Label ID="lblEndTime" Text="End Time:" AssociatedControlID="txtTime" runat="server" /> <asp:TextBox ID="txtEndTime" Width="100" runat="server" /> <cc1:TimeExtender ID="timepickerEndTime" TargetControlID="txtEndTime" ShowAMandPM="true" ShowButton="true" runat="server" /> </div> <div class="divClearFloat"></div> </div> </ContentTemplate> </asp:UpdatePanel> </asp:Content>
Он успешно выполняет эту задачу, но выдает ошибку времени выполнения, например
The TargetControlID of 'PopupControlExtender_Time' is not valid. The value cannot be null or empty.
Пожалуйста помогите me.it-это срочно.