Thursday, August 12, 2010

How to get current week start date from current date in .NET

Following code will give you the week start date on passing any date.


private DateTime getWeekStartDate(DateTime weekDate)
{
DateTime currentWeekStartDate = weekDate;

string StartDay = "1" // You can set any day as start day of the week
// 1 for monday, 2 for tuesday and so on

while (!StartDay.ToLower().Equals(currentWeekStartDate.DayOfWeek.ToString().ToLower()))
{
currentWeekStartDate = currentWeekStartDate.Subtract(new TimeSpan(1, 0, 0, 0));
}
return currentWeekStartDate
}

Hope this helps, thanks

How to catch a drop down event from a datalist and have a cascading effect.

Many a times in projects we have come across a need to get a drop down event from a datalist for a particular row, here is the code how you can achieve it.

1. In your data list set the selected index change event of the drop down and set the AutpPostBack Property to true.

2. Write the code as below

protected void ddlYourDropDown_SelectedIndexChanged(object sender, EventArgs e)
{

DropDownList ddlYourDropDown= (DropDownList)sender;


//So here you got the dropdown from the datalist row
// do whatever you want

}

Once you get the particular drop down from the datalist you can do whatever you want with its value, for example, if you need to have a cascading effect of drop downs within your data list, then you can acieve it very easily as below.

protected void ddlParentDropDown_SelectedIndexChanged(object sender, EventArgs e)
{

DropDownList ddlParentDropDown_= (DropDownList)sender;
DataListItem dataListItem = (DataListItem)ddl.Parent; // get the datalistitem you select to get the drop down to which you want to populate based on the parent drop down

DropDownList ddlChildDropDown= (DropDownList)dataListItem.FindControl("ddlChildDropDown");
ddlChildDropDown.Items.Clear();
if (ddlParentDropDown!= null && ddlChildDropDown!= null)
{
if (ddlParentDropDown.SelectedIndex != 0)
{
//populate Child drop down with parent drop down's (ddlParentDropDown) value

}
}