views:

112

answers:

2

I have a custom control that print the current date into the page. The control has a Format property for setting witch DateTime property to be printed. (Date, Day, Year etc...)

<TSC:DateTimeWriter runat="server" Format="Year" />

But what i want is when i type :

Format="

I want to show a list of all the possible values(Using Visual Studio).

The cs code:

public class DateTimeWriter : Control
{
 public string Format { get; set; }

 protected override void Render(HtmlTextWriter writer)
 {
  writer.Write(writeDateTime());
 }

 private string writeDateTime()
 {
  var now = DateTime.Now;
  switch (Format)
  {
   case "Year":
    return now.Year.ToString();
   case "Day":
    return now.Day.ToString();
   etc...
   default:
    return now.ToString();
  }
 }
}
+1  A: 

Create an enumerated Type

namespace YourNameSpace

{

[Serializable()]

public enum DateFormat

{

    Date,

    Day,

    Year

}

}

then add a property to your control:

    /// <summary>
    /// Date Format
    /// </summary>
    public DateFormat DateFormat
    {
        get
        {
            if (ViewState["DateFormat"] == null || ViewState["DateFormat"].ToString().Trim() == String.Empty)
            {
                return DateFormat.Date;  //Default
            }
            return (DateFormat)ViewState["DateFormat"];
        }
        set
        {
            ViewState["DateFormat"] = value;
        }
    }
Mark Redman
The Enum part is correct. but if i use the control several placec within a page the ViewState stuff will not work. Or am I wrong ?
Thomas Sandberg
The ViewState will be tied to the instance of the WebControl, so you can have multiple controls on one page and they wont conflict.
Mark Redman
+2  A: 

If you make the Format property an enum instead of a string, VS will be able to display a list of supported formats. E.g.:

public enum DateTimeFormat
{
    Year,
    ...
}
Peter Lillevold