Click here to Skip to main content
15,897,718 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello,

I am new to the time selector concept in asp.net,while searching i got the following link.

ASP.NET 4.0 TimePicker User Control[^]

This link works same exactly i want.When i download project it works well.
But problem is that developed using vb.net language, same code i want in C# language.

Please help me.

What I have tried:

Here i added Web User control in my project i.e
WebUserControl1.ascx
.
this my WebUserControl1.ascx page code
<%@ 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>


And this is code behind page code
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;
        }
    }
}


And this my default.aspx page
<%@ 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>

It complies successfully, but gives run time error like
The TargetControlID of 'PopupControlExtender_Time' is not valid. The value cannot be null or empty. 


Please help me.it's urgent.
Posted
Updated 31-Oct-18 21:08pm

1 solution

Quote:
Please help me.it's urgent.
No, it isn't. I checked, and nobody here has it even on their top 100 "things to do this year" list. It's urgent to you, but every question is urgent to the author. All that your stressing the urgency does is to make us think you have left it too late, and want us to do it for you. This annoys some people, and can slow a response.

Now, to the problem.
First off, if you have a problem with code from an article, then there is a "Add a Comment or Question" button at the bottom of that article, which causes an email to be sent to the author. They are then alerted that you wish to speak to them.
Posting this here relies on them "dropping by" and realising it is for them.

Secondly, if doesn't matter what language it is written in. Compile VB code to a DLL and you can use it in C# or VB code; compile C# code to a DLL and you can do exactly the same. All .NET framework code compiles to IL which is not original language specific.

Your error message is pretty specific: The ID is not null or empty. Since you don't show the code you use to assign a value to PopupControlExtender_Time (or even the definition of it) we can't help you. Use the debugger to look at the value, and see exactly what you are doing with it!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900