Wednesday, June 22, 2011

SharePoint DateTimeControl

I needed to use the SharePoint DateTimeControl, first issue I faced is settting the date format, second issue is setting error messages and finally the location where the validation messages appear i needed to change it

I declared a new class NewDateTimeControl inherited from DateTimeControl
I overrided its OnInit method and Render virtual methods
  1. At the OnInit I changed the control properties LocaleId, MinDate and Error Messages appearing
  2. At the Render method i changed the way the control is rendered, required field validators are renendered as html span tag so I just read the whole span html and placed it after the closing tag of the iframe used to display the calendar
public class NewDateTimeControl:DateTimeControl
{
private const string SPAN_TAG = "<span";
private const string IFRAME_CLOSE_TAG = "</iframe>";
protected override void OnInit(EventArgs e)
{
base.OnInit(e);

LocaleId = SPContext.Current.Web.Locale.LCID;

string dateCtrlID = this.ID + "Date";

TextBox tbDate = ((TextBox)this.FindControl(dateCtrlID));



if (MinDate == DateTime.MinValue)

this.MinDate = DateTime.Now.Date;



RequiredFieldValidator reqVal = ((RequiredFieldValidator)this.Controls[5]);

reqVal.Display = ValidatorDisplay.Dynamic;

reqVal.ToolTip = TGOHelper.DateRequiredErrorMsg;

if (!string.IsNullOrEmpty(ValidationGroup) && this.IsRequiredField)

{

reqVal.ValidationGroup = ValidationGroup;

reqVal.ErrorMessage =
TGOHelper.DateRequiredErrorMsg;

}

reqVal.Text =
"*&nbsp;";

}

protected override void Render(System.Web.UI.HtmlTextWriter output)
{
//Read output html in sb string

StringBuilder sb = new StringBuilder();

HtmlTextWriter tw = new HtmlTextWriter(new System.IO.StringWriter(sb));

base.Render(tw);

            //alter sb string to reposition your validator

string outPutHTML = sb.ToString();

int spanIndex = outPutHTML.IndexOf(SPAN_TAG);

string spanString = outPutHTML.Substring(spanIndex, outPutHTML.Length - spanIndex);

outPutHTML = outPutHTML.Substring(0, spanIndex);

int lastFrameIndex = outPutHTML.LastIndexOf(IFRAME_CLOSE_TAG);

lastFrameIndex += IFRAME_CLOSE_TAG.Length;

outPutHTML = outPutHTML.Insert(lastFrameIndex, spanString);
     

//write your new output HTML

output.Write(outPutHTML);

}
public string ValidationGroup
{
set { ViewState["ValidationGroup"] = value; }
get {
if (null == ViewState["ValidationGroup"])
return string.Empty;
return ViewState["ValidationGroup"].ToString();

}

}