Monday, October 26, 2009

Using the SharePoint date control in a web part

After a lot of requests in comments in this blog, I figured this must be very hard to implement. So I tried, and found it quite easy. Here is a code sample of a web part that uses the sharepoint date control

The code is simple - three controls - a DateTimeControl from the Microsoft.SharePoint.WebControls namespace, a button and a text box.
The button has a click event. On click, the event sets the text box to display the date that was selected in the DateTimeControl.


public class DatePickerWebPart : System.Web.UI.WebControls.WebParts.WebPart {
DateTimeControl dtc;
TextBox t;
Button b;

protected override void CreateChildControls()
{
base.CreateChildControls();
dtc = new DateTimeControl();
dtc.ID = "dtc" + this.UniqueID;
this.Controls.Add(dtc);
b = new Button();
b.Text = "Click me to see the date";
this.Controls.Add(b);
b.Click += new EventHandler(b_Click);
t = new TextBox();
this.Controls.Add(t);
}

void b_Click(object sender, EventArgs e)
{
t.Text = dtc.SelectedDate.ToLongDateString();
}
}

Here is the result:

This is the web part when the page first loads


This is the web part when you click on the date picker


This is the web part when you click on the button

0 comments: