Wednesday, February 20, 2008

Asp.Net : Implementing Date Selection without CalendarExtender Ajax Control

Thought implementing Date Selection options with CalendarExtender Ajax Control is a breeze, many ASP.Net Programmers are still working with Asp.net 1.x.
With a bit of nostalgic tint let me blog on the code I used to write to implement the same functionality in Asp.Net 1.x.

I start out with placing three combo boxes for Day, Month and Year and fill the controls with valuues. Then catenated values of three comboxes will be committed to table.

Here is the code:

using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
SqlConnection cnn;
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillDayCombo();
FillMonthCombo();
FillYearCombo();
DataBind();
}
cnn = new SqlConnection("Integrated Security=sspi;Initial Catalog=Shalvin;Data Source=.\\sqlexpress");
cnn.Open();
}

protected void FillDayCombo()
{
for (int i = 1; i < 31; i++)
ddlDay.Items.Add(i.ToString());
}
protected void FillMonthCombo()
{
string[] strMonths = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec" };
ddlMonth.DataSource = strMonths;
}
protected void FillYearCombo()
{
for (int i = 1990; i < 2020; i++)
ddlYear.Items.Add(i.ToString());
}

protected void Button1_Click(object sender, EventArgs e)
{
string strDate = ddlDay.Text.ToString() + "-" + ddlMonth.Text.ToString() + "-" + ddlYear.Text.ToString();
Response.Write(strDate);
cmd = new SqlCommand("Insert into DateTest values ('" + strDate + "')", cnn);
cmd.ExecuteNonQuery();
Response.Write("Record Saved");
}
}


MultiTier

Now let's implement the same solution in Multi tier scenario.
I am creating a class called DBConnect.

public class DbConnect
{
public ArrayList GetDays()
{
ArrayList alDays = new ArrayList();
for (int i = 1; i < 31; i++)
alDays.Add(i.ToString());
return alDays;
}
public string[] GetMonths()
{
string[] strMonths = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec" };
return strMonths;
}
public ArrayList GetYears()
{
ArrayList alYears = new ArrayList();
for (int i = 1990; i < 2020; i++)
alYears.Add (i.ToString());
return alYears;
}

Coming back to the form I am instantiating the DbConnect class and callilng its methods.
DbConnect dbc = new DbConnect();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlDay.DataSource = dbc.GetDays();
ddlMonth.DataSource = dbc.GetMonths();
ddlYear.DataSource = dbc.GetYears();
DataBind();
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
string str = ddlDay.Text + "-" + ddlMonth.Text + "-" + ddlYear.Text;
Response.Write(str);
}


Happy Programming
Shalvin@gmail.com

No comments:

Post a Comment