Hi Paul,
There may be other ways to do this but here are some sample steps. I would
encourage you to complete these so you can see how this works - then
migrate this to your application:
- Create a new, blank InfoPath form (using .NET)
- Add 2 Date Picker controls (field1 and field2), a text box (field3) and a
button
- Right-click on the button, choose Properties and click the Edit Form Code
button (this should launch your C# editor)
- Add the following line of code for the button click event:
showDayOfWeek();
- Add the following showDayOfWeek procedure:
public void showDayOfWeek()
{
//Get references to the start date, end date and elapsed days fields on
the form
IXMLDOMNode oDateStart =
thisXDocument.DOM.selectSingleNode("//my:myFields/my:field1");
IXMLDOMNode oDateEnd =
thisXDocument.DOM.selectSingleNode("//my:myFields/my:field2");
IXMLDOMNode oElapsedDays =
thisXDocument.DOM.selectSingleNode("//my:myFields/my:field3");
//Store the start date and end date values from the fields
DateTime s = Convert.ToDateTime(oDateStart.text);
DateTime e = Convert.ToDateTime(oDateEnd.text);
//Store the start date day of the week - this is used to determine if
//the start date "day" is a weekday - if it is, we subtract one day from
//the elapsed days
string strStartDay = s.DayOfWeek.ToString();
//Boolean flag for setting if the start date is a weekday
bool startIsWeekday = false;
//Counter used to increment weekdays
int i = 0;
//Array to store weekdays
string[] Weekdays = new string[5] {"Monday", "Tuesday", "Wednesday",
"Thursday", "Friday"};
//Loop while the selected start date is <= the selected end date
while (s <= e)
{
//Get the weekday of the current date
string curDay = s.DayOfWeek.ToString();
//Check to see if the current date (curDay) is a weekday in the array
foreach(string strDay in Weekdays)
if(curDay == strDay)
{
//If it is a weekday, increment the counter
i += 1;
//If the start date day is a weekday, decrement the counter
if(startIsWeekday == false && curDay == strStartDay)
{
startIsWeekday = true;
i -= 1;
}
}
//Get the next date
s = s.AddDays(1);
};
//Set the value of the elapsed days field to the counter value
oElapsedDays.text = i.ToString();
//Clean up
oDateStart = null;
oDateEnd = null;
oElapsedDays = null;
}
- Build the project and run
- Choose 7/1/2005 as a start date
- Choose 7/29/2005 as an end date
- Click the button - you should get 20 in the elapsed days field
- If you now choose 7/2 or 7/3 as a start date you will still get 20
elapsed days but if you select 7/4, the elapsed days will be 19.
** NOTE: This is only sample code with the following caveats:
- It does not check for date fields being blank
- It does not check to insure the end date is later than the start date
- It does not take into consideration holidays, in which the date can
obviously vary each year
I hope this helps!
Scott L. Heim
Microsoft Developer Support
This posting is provided "AS IS" with no warranties, and confers no rights.