Tuesday, August 24, 2010

Pull a column value from another list in your site in Sharepoint Portal Server


I have a list of Projects in SharePoint called as "Projects" and list contains following columns:

1. Project Name
2. Project Manager
3. Status

I want to make another list called "Project Milestones" where one of the fields in this list would be the name of the Project from the "Projects" list.
Is there a way to have this be a drop down that points to the "Project Name" field from the "Projects" List?

Of course, yes! We can pull data from other lists to be displayed in our list.

Here is the answer to the question emailed by the user:

1. Add a new column in your "ProjectMilestones" list. This is the list where you want to show data from the other list. This can a document library or a form library, depending on your needs.
2. Name the new column as "ProjectName".
3. Column type should be "Lookup"
4. In the "Get Information From:" drop down under "Optional Settings for
Column", select "Projects" list.
5. In "In this column" drop down, select "Project Name".
6. Click OK.



This newly added field will display project names from the "Projects" list.

Let's talk about the lookup field a bit. Lookup field refers to values from a field in another list as you saw above. It's a great way of linking two lists together. You can easily pull column values from different lists already available in your site. If you are a programmer like me, then you may want to look at the way how we can add a lookup field to the form programmatically. Here is the code:

SPSite site = SPControl.GetContextSite(Context);
SPFieldCollection fields = site.AllWebs["mysite"].Lists["mylist"].Fields;

SPList lookupList = site.AllWebs["mysite"].Lists["mylookuplist"];

Guid lkListID = lookupList.ID;

fields.AddLookup("Lookup_FieldName", lkListID, true);

If you work regularly with SharePoint, then you will find this tip to be very helpful.

Calculated column Formula- sharepoint

You can use the following examples in calculated columns. Examples that do not include column references can be used to specify the default value of a column.
Conditional formulas
Check if a number is greater than or less than another number
Use the IF function to do this task.
Column1 Column2 Formula Description
15000 9000 =Column1>Column2 Is Column1 greater than Column2? (Yes)
15000 9000 =IF(Column1<=Column2, "OK", "Not OK") Is Column1 less than or equal to Column2? (Not OK)
Return a logical value after comparing column contents
For a result that is a logical value (Yes or No), use the AND, OR, and NOT functions.
Column1 Column2 Column3 Formula Description
15 9 8 =AND(Column1>Column2, Column115 9 8 =OR(Column1>Column2, Column115 9 8 =NOT(Column1+Column2=24) Is 15 plus 9 not equal to 24? (No)
For a result that is another calculation, or any other value other than Yes or No, use the IF, AND, and OR functions.
Column1 Column2 Column3 Formula Description
15 9 8 =IF(Column1=15, "OK", "Not OK") If the value in Column1 equals 15, then return "OK". (OK)
15 9 8 =IF(AND(Column1>Column2, Column115 9 8 =IF(OR(Column1>Column2, Column1Display zeroes as blanks or dashes
Use the IF function to do this task.
Column1 Column2 Formula Description
10 10 =Column1-Column2 Second number subtracted from the first (0)
15 9 =IF(Column1-Column2,"-",Column1-Column2) Returns a dash when the value is zero (-)
Date and time formulas
Add dates
To add a number of days to a date, use the addition (+) operator. Note that when manipulating dates, the return type of the calculated column must be set to Date and Time.
Column1 Column2 Formula Description
6/9/2007 3 =Column1+Column2 Add 3 days to 6/9/2007 (6/12/2007)
12/10/2008 54 =Column1+Column2 Add 54 days to 12/10/2008 (2/2/2009)
To add a number of months to a date, use the DATE, YEAR, MONTH, and DAY functions.
Column1 Column2 Formula Description
6/9/2007 3 =DATE(YEAR(Column1),MONTH(Column1)+Column2,DAY(Column1)) Add 3 months to 6/9/2007 (9/9/2007)
12/10/2008 25 =DATE(YEAR(Column1),MONTH(Column1)+Column2,DAY(Column1)) Add 25 months to 12/10/2008 (1/10/2011)
To add a number of years to a date, use the DATE, YEAR, MONTH, and DAY functions.
Column1 Column2 Formula Description
6/9/2007 3 =DATE(YEAR(Column1)+Column2,MONTH(Column1),DAY(Column1)) Add 3 years to 6/9/2007 (6/9/2010)
12/10/2008 25 =DATE(YEAR(Column1)+Column2,MONTH(Column1),DAY(Column1)) Add 25 years to 12/10/2008 (12/10/2033)
To add a combination of days, months, and years to a date, use the DATE, YEAR, MONTH, and DAY functions.
Column1 Formula Description
6/9/2007 =DATE(YEAR(Column1)+3,MONTH(Column1)+1,DAY(Column1)+5) Add 3 years, 1 month, and 5 days to 6/9/2007 (1/14/2009)
12/10/2008 =DATE(YEAR(Column1)+1,MONTH(Column1)+7,DAY(Column1)+5) Add 1 year, 7 months, and 5 days to 6/9/2007 (7/15/2010)
Calculate the difference between two dates
Use the DATEDIF function to do this task.
Column1 Column2 Formula Description
01-Jan-1995 15-Jun-1999 =DATEDIF(Column1, Column2,"d") Return the number of days between the two dates (1626)
01-Jan-1995 15-Jun-1999 =DATEDIF(Column1, Column2,"ym") Return the number of months between the dates, ignoring the year part (5)
01-Jan-1995 15-Jun-1999 =DATEDIF(Column1, Column2,"yd") Return the number of days between the dates, ignoring the year part (165)
Calculate the difference between two times
For presenting the result in the standard time format (hours:minutes:seconds), use the subtraction operator (-) and the TEXT function. For this method to work, hours must not exceed 24, and minutes and seconds must not exceed 60.
Column1 Column2 Formula Description
06/09/2007 10:35 AM 06/09/2007 3:30 PM =TEXT(Column2-Column1,"h") Hours between two times (4)
06/09/2007 10:35 AM 06/09/2007 3:30 PM =TEXT(Column2-Column1,"h:mm") Hours and minutes between two times (4:55)
06/09/2007 10:35 AM 06/09/2007 3:30 PM =TEXT(Column2-Column1,"h:mm:ss") Hours,minutes, and seconds between two times (4:55:00)
For presenting the result in a total based on one time unit, use the INT function, or HOUR, MINUTE, and SECOND functions.
Column1 Column2 Formula Description
06/09/2007 10:35 AM 06/10/2007 3:30 PM =INT((Column2-Column1)*24) Total hours between two times (28)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =INT((Column2-Column1)*1440) Total minutes between two times (1735)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =INT((Column2-Column1)*86400) Total seconds between two times (104100)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =HOUR(Column2-Column1) Hours between two times, when the difference does not exceed 24. (4)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =MINUTE(Column2-Column1) Minutes between two times, when the difference does not exceed 60. (55)
06/09/2007 10:35 AM 06/10/2007 3:30 PM =SECOND(Column2-Column1) Seconds between two times, when the difference does not exceed 60. (0)
Convert times
To convert hours from standard time format to a decimal number, use the INT function.
Column1 Formula Description
10:35 AM =(Column1-INT(Column1))*24 Number of hours since 12:00 AM (10.583333)
12:15 PM =(Column1-INT(Column1))*24 Number of hours since 12:00 AM (12.25)
To convert hours from a decimal number to the standard time format (hours:minutes:seconds), use the divisor operator and the TEXT function.
Column1 Formula Description
23:58 =TEXT(Column1/24, "hh:mm:ss") Hours, minutes, and seconds since 12:00 AM (00:59:55)
2:06 =TEXT(Column1/24, "h:mm") Hours and minutes since 12:00 AM (0:05)
Insert Julian dates
The phrase "Julian date" is sometimes used to refer to a date format that is a combination of the current year, and the number of days since the beginning of the year. For example, January 1, 2007 is represented as 2007001 and December 31, 2007 is represented as 2003356. This format is not based on the Julian calendar.
To convert a date to a Julian date, use the TEXT and DATEVALUE functions.
Column1 Formula Description
6/23/2007 =TEXT(Column1,"yy")&TEXT((Column1-DATEVALUE("1/1/"& TEXT(Column1,"yy"))+1),"000") Date in "Julian" format, with a two-digit year (07174)
6/23/2007 =TEXT(Column1,"yyyy")&TEXT((Column1-DATEVALUE("1/1/"&TEXT(Column1,"yy"))+1),"000") Date in "Julian" format, with a four-digit year (2007174)
To convert a date to a Julian date used in astronomy, use the constant 2415018.50. This formula only works for dates after 3/1/1901, and if you are using the 1900 date system.
Column1 Formula Description
6/23/2007 =Column1+2415018.50 Date in "Julian" format, used in astronomy (2454274.50)
Show dates as the day of the week
To convert dates to the text for the day of the week, use the TEXT and WEEKDAY functions.
Column1 Formula Description
19-Feb-2007 =TEXT(WEEKDAY(Column1), "dddd") Calculates the day of the week for the date and returns the full name of the day (Monday)
3-Jan-2008 =TEXT(WEEKDAY(Column1), "ddd") Calculates the day of the week for the date and returns the abbreviated name of the day (Thu)
Math formulas
Add numbers
To add numbers in two or more columns in a row, use the addition operator (+) or the SUM function.
Column1 Column2 Column3 Formula Description
6 5 4 =Column1+Column2+Column3 Add the values in the first three columns (15)
6 5 4 =SUM(Column1,Column2,Column3) Add the values in the first three columns (15)
6 5 4 =SUM(IF(Column1>Column2, Column1-Column2, 10), Column3) If Column1 is greater than Column2, add the difference and Column3. Else add 10 and Column3. (5)
Subtract numbers
Use the subtraction (-) operator to do this task.
Column1 Column2 Column3 Formula Description
15000 9000 -8000 =Column1-Column2 Subtract 9000 from 15000 (6000)
15000 9000 -8000 =SUM(Column1, Column2, Column3) Add numbers in the first three columns, including negative values (16000)
Calculate the difference between two numbers as a percentage
Use the subtraction (-) and division (/) operators, and the ABS function.
Column1 Column2 Formula Description
2342 2500 =(Column2-Column1)/ABS(Column1) Percentage change (6.75% or 0.06746)
Multiply numbers
Use the multipliation (*) operator or the PRODUCT function to do this task.
Column1 Column2 Formula Description
5 2 =Column1*Column2 Multiplies the numbers in the first two columns (10)
5 2 =PRODUCT(Column1, Column2) Multiplies the numbers in the first two columns (10)
5 2 =PRODUCT(Column1,Column2,2) Multiplies the numbers in the first two columns and the number 2 (20)
Divide numbers
Use the division operator (/) to do this task.
Column1 Column2 Formula Description
15000 12 =Column1/Column2 Divides 15000 by 12 (1250)
15000 12 =(Column1+10000)/Column2 Adds 15000 and 10000, and then divides the total by 12 (2,083)
Calculate the average of numbers
The average is also called the mean. To calculate the average of numbers in two or more columns in a row, use the AVERAGE function.
Column1 Column2 Column3 Formula Description
6 5 4 =AVERAGE(Column1, Column2,Column3) Average of the numbers in the first three columns (5)
6 5 4 =AVERAGE(IF(Column1>Column2, Column1-Column2, 10), Column3) If Column1 is greater than Column, calculate the average of the difference and Column3. Else calculate the average of the value 10 and Column3. (2.5)
Calculate the median of numbers
The median is the value at the center of an ordered range of numbers. Use the MEDIAN function to calculate the median of a group of numbers.
A B C D E F Formula Description
10 7 9 27 0 4 =MEDIAN(A, B, C, D, E, F) Median of numbers in the first 6 columns (8)
Calculate the smallest or largest number in a range
To calculate the smallest or largest number in two or more columns in a row, use the MIN and MAX functions.
Column1 Column2 Column3 Formula Description
10 7 9 =MIN(Column1, Column2, Column3) Smallest number (7)
10 7 9 =MAX(Column1, Column2, Column3) Largest number (10)
Count values
To count numeric values, use the COUNT function.
Column1 Column2 Column3 Formula Description
Apple 12/12/2007 =COUNT(Column1, Column2, Column3) Counts the number of columns that contain numeric values. Excludes date and time, text, and null values.(0)
12 #DIV/0! 1.01 =COUNT(Column1, Column2, Column3) Counts the number of columns that contain numeric values, but excludes error and logical values (2)
Increase or decrease a number by a percentage
Use the percentage (%) operator to do this task.
Column1 Column2 Formula Description
23 3% =Column1*(1+5%) Increases number in Column1 by 5% (24.15)
23 3% =Column1*(1+Column2) Increase number in Column1 by the percent value in Column2: 3% (23.69)
23 3% =Column1*(1-Column2) Decrease number in Column1 by the percent value in Column2: 3% (22.31)
Raise a number to a power
Use the exponent (^) operator or the POWER function to do this task.
Column1 Column2 Formula Description
5 2 =Column1^Column2 Calculates five squared (25)
5 3 =POWER(Column1, Column2) Calculates five cubed (125)
Round a number
To round up a number, use the ROUNDUP, ODD, and EVEN functions.
Column1 Formula Description
20.3 =ROUNDUP(Column1,0) Rounds 20.3 up to the nearest whole number (21)
-5.9 =ROUNDUP(Column1,0) Rounds -5.9 up (-6)
12.5493 =ROUNDUP(Column1,2) Rounds 12.5493 up to the nearest hundredth, two decimal places (12.55)
20.3 =EVEN(Column1) Rounds 20.3 up to the nearest even number (22)
20.3 =ODD(Column1) Rounds 20.3 up to the nearest odd number (21)
To round down a number, use the ROUNDDOWN function.
Column1 Formula Description
20.3 =ROUNDDOWN(Column1,0) Rounds 20.3 down to the nearest whole number (20)
-5.9 =ROUNDDOWN(Column1,0) Rounds -5.9 down (-5)
12.5493 =ROUNDDOWN(Column1,2) Rounds 12.5493 down to the nearest hundredth, two decimal places (12.54)
To round a number to the nearest number or fraction, use the ROUND function.
Column1 Formula Description
20.3 =ROUND(Column1,0) Rounds 20.3 down, because the fraction part is less than .5 (20)
5.9 =ROUND(Column1,0) Rounds 5.9 up, because the fraction part is greater than .5 (6)
-5.9 =ROUND(Column1,0) Rounds -5.9 down, because the fraction part is less than -.5 (-6)
1.25 =ROUND(Column1, 1) Rounds the number to the nearest tenth (one decimal place). Because the portion to be rounded is 0.05 or greater, the number is rounded up (result: 1.3)
30.452 =ROUND(Column1, 2) Rounds the number to the nearest hundredth (two decimal places). Because the portion to be rounded, 0.002, is less than 0.005, the number is rounded down (result: 30.45)
To round a number to the significant digit above 0, use the ROUND, ROUNDUP, ROUNDDOWN, INT, and LEN functions.
Column1 Formula Description
5492820 =ROUND(Column1,3-LEN(INT(Column1))) Rounds the number to 3 significant digits (5490000)
22230 =ROUNDDOWN(Column1,3-LEN(INT(Column1))) Rounds the bottom number down to 3 significant digits (22200)
5492820 =ROUNDUP(Column1, 5-LEN(INT(Column1))) Rounds the top number up to 5 significant digits (5492900)
Text formulas
Change the case of text
Use the UPPER, LOWER, or PROPER functions to do this task.
Column1 Formula Description
nancy Davolio =UPPER(Column1) Changes text to uppercase (NANCY DAVOLIO)
nancy Davolio =LOWER(Column1) Changes text to lowercase (nancy davolio)
nancy Davolio =PROPER(Column1) Changes text to title case (Nancy Davolio)
Combine first and last names
Use the ampersand (&) operator or the CONCATENATE function to do this task.
Column1 Column2 Formula Description
Nancy Fuller =Column1&Column2 Combines the two strings (NancyFuller)
Nancy Fuller =Column1&" "&Column2 Combines the two strings, separated by a space (Nancy Fuller)
Nancy Fuller =Column2&","&Column1 Combines the two strings, separated by a comma (Fuller,Nancy)
Nancy Fuller =CONCATENATE(Column2, ",", Column1) Combines the two strings, separated by a comma (Fuller,Nancy)
Combine text and numbers from different columns
Use the CONCATENATE and TEXT functions, and the ampersand (&) operator to do this task.
Column1 Column2 Formula Description
Buchanan 28 =Column1&" sold "&Column2&" units." Combines contents above into a phrase (Buchanan sold 28 units)
Dodsworth 40% =Column1&" sold "&TEXT(Column2,"0%")&" of the total sales." Combines contents above into a phrase (Dodsworth sold 40% of the total sales).
Note The TEXT function appends the formatted value of Column2 instead of the underlying value, which is .4.
Buchanan 28 =CONCATENATE(Column1," sold ",Column2," units.") Combines contents above into a phrase (Buchanan sold 28 units)
Combine text with a date or time
Use the TEXT function and the ampersand (&) operator to do this task.
Column1 Column2 Formula Description
Billing Date 5-Jun-2007 ="Statement date: "&TEXT(Column2, "d-mmm-yyyy") Combine text with a date (Statement date: 5-Jun-2007)
Billing Date 5-Jun-2007 =Column1&" "&TEXT(Column2, "mmm-dd-yyyy") Combine text and date from difference columns into one column (Billing Date Jun-05-2007)
Compare column contents
To compare one column to another column or a list of values, use the EXACT function.
Column1 Column2 Formula Description
BD122 BD123 =EXACT(Column1,Column2) Compare contents of first two columns (No)
BD122 BD123 =EXACT(Column1,"BD122") Compare contents of Column1 and the string "BD122" (Yes)
Check if a column value or a part of it matches specific text
To check if a column value or a part of it matches specific text, use the IF, FIND, SEARCH, and ISNUMBer functions.
Column1 Formula Description
Davolio =IF(Column1="Davolio", "OK", "Not OK") Checks to see if Column1 is Davolio (OK)
Davolio =IF(ISNUMBER(FIND("v",Column1)), "OK", "Not OK") Checks to see if Column1 contains the letter v (OK)
BD123 =ISNUMBER(FIND("BD",Column1)) Checks to see if Column1 contains BD (Yes)
Count nonblank columns
Use the COUNTA function to do this task.
Column1 Column2 Column3 Formula Description
Sales 19 =COUNTA(Column1, Column2) Counts the number of nonblank columns (2)
Sales 19 =COUNTA(Column1, Column2, Column3) Counts the number of nonblank columns (2)
Remove characters from text
Use the LEN, LEFT, and RIGHT functions to do this task.
Column1 Formula Description
Vitamin A =LEFT(Column1,LEN(Column1)-2) Return 7 (9-2) characters, starting from left (Vitamin)
Vitamin B1 =RIGHT(Column1, LEN(Column1)-8) Return 2 (10-8) characters, starting from right (B1)
Remove spaces from the beginning and end of a column
Use the TRIM function to do this task.
Column1 Formula Description
Hello there! =TRIM(Column1) Remove the spaces from the beginning and end (Hello there!)
Repeat a characater in a column
Use the REPT function to do this task.
Formula Description
=REPT(".",3) Repeats a period 3 times (...)
=REPT("-",10) Repeats a dash 10 times (----------)
Other formulas
Hide error values in columns
To display a dash, #N/A, or NA in place of an error value, use the ISERROR function.
Column1 Column2 Formula Description
10 0 =Column1/Column2 Results in an error (#DIV/0)
10 0 =IF(ISERROR(Column1/Column2),"NA",Column1/Column2) Returns NA when the value is an error
10 0 =IF(ISERROR(Column1/Column2),"-",Column1/Column2) Returns a dash when the value is an error
Did this article help you?

Saturday, August 21, 2010

Friday, August 6, 2010

ASP >NET FREE WEB HOSTING SITE

http://www.websamba.com 30
http://www.cfm-resources.com 30
http://www.brinkster.com 30
http://www.7host.com 50
http://www.maxipointservers.net 20
http://www.ionwd.com ?
http://www.1asphost.com 100
http://www.everanet.com ?

Wednesday, July 21, 2010

Tuesday, July 20, 2010

MSDN SHAREPOINT PART FOR U

http://msdn.microsoft.com/hi-in/office/cc990283(en-us).aspx

Creating a Contact Form Web Part for SharePoint

http://www.cinlogic.com/Articles/2/Creating-a-Contact-Form-Web-Part-For-SharePoint.aspx

Introduction
SharePoint is a powerful application that enables an organization to quickly implement a web based portal for managing and sharing information among groups of people. Out of the box it offers many components such as document libraries and configurable lists. For more advanced requirements, SharePoint provides the ability to create web parts, which are custom components that can plug into and interact with a SharePoint site. Web parts are a simple, yet powerful way to extend the capabilities of SharePoint to meet your organization’s unique requirements.

This article will show, step-by-step, how to create a simple SharePoint web part that implements a contact form. A contact form is typically used on a public website to provide a way for customers, business partners, and others outside the company to submit questions or request information by filling out fields on a web page and clicking a submit button. This web part will collect the user’s name, email address, phone number, and message, and send the information to an email address when the user clicks Submit.



Requirements
The web part created in this article will use Windows SharePoint Services (WSS) 3.0. It will also work with MOSS 2007, which is a more advanced version of SharePoint built on the same infrastructure as WSS 3.0. To create the web part, we will be using Visual Studio 2008 installed on Windows Server 2003, along with Windows SharePoint Services 3.0 Tools: Visual Studio 2008 Extensions, Version 1.2, which is a free download from the Microsoft Download Center.

Creating a Web Part Project
The first step is to create a new web part project using Visual Studio 2008. To do this, open Visual Studio 2008 and choose New – Project from the file menu. Select Visual C# - SharePoint from the Project Type List, and select the Web Part template from the list on the right. Enter ContactFormWebPart as the name and the solution name and choose a directory where you want the solution files to be saved. When you click OK, an empty web part project will be created and opened in Visual Studio.

The empty project has one web part, called WebPart1, but this isn’t what we want to call our web part, so the first step is to delete WebPart1 from the project by right clicking on the WebPart1 folder in Solution Explorer in Visual Studio and choosing Delete.

Next, let's add a new web part to the project, called ContactForm. Right click on the ContactFormWebPart project in solution explorer, and choose Add – New Item from the context menu. Select SharePoint from the categories list, and Web Part from the templates list. Enter ContactForm for the name and click Add.



This gives you a new source file called ContactForm.cs that has an empty class inheriting from WebPart with some TODO comments. In the next section, we are going to replace the CreateChildControls() function and add some additional code to this class.



Adding Code to Create the Controls
Now we are ready to begin writing code that will display the web part. Open ContactForm.cs and you will see a function called CreateChildControls(). This function is where we will add labels, textboxes, and a button to allow the user to interact with our web part.

But first, let's create some class-level variables for the controls that we will create. Declaring them at the class level as opposed to within the CreateChildControls() function will allow us to reference these controls from the button event handler later on.


TextBox txtContactName;
TextBox txtEmailAddress;
TextBox txtPhone;
TextBox txtMessage;
Button btnSendMessage;
Label lblMessageSent;

Now lets add the code to CreateChildControls to build the display. In order to keep it simple, an HTML table will be used to align the controls in a consistent manner. Each table row will have two cells: One for the field label and the other for the text boxes. Controls are created one at a time and added to a table cell, which is then added to a table row.


protected override void CreateChildControls()
{
base.CreateChildControls();

Table t;
TableRow tr;
TableCell tc;

// A table that is used to layout the controls
t = new Table();

// Label with instructions for the user
tr = new TableRow();
tc = new TableCell();
tc.ColumnSpan = 2;
tc.VerticalAlign = VerticalAlign.Top;
Label lblInstructions = new Label();
lblInstructions.Text = "Please enter your contact information and message below.";
tc.Controls.Add(lblInstructions);
tr.Controls.Add(tc);

t.Controls.Add(tr);

// Contact Name label
tr = new TableRow();
tc = new TableCell();
tc.Style["padding-top"] = "7px";
tc.VerticalAlign = VerticalAlign.Top;
Label lblContactName = new Label();
lblContactName.Text = "Name:";
tc.Controls.Add(lblContactName);
tr.Controls.Add(tc);

// Contact Name textbox
tc = new TableCell();
tc.VerticalAlign = VerticalAlign.Top;
txtContactName = new TextBox();
txtContactName.ID = "txtContactName";
txtContactName.Width = Unit.Pixel(300);
tc.Controls.Add(txtContactName);
tr.Controls.Add(tc);

t.Controls.Add(tr);

// Email Address label
tr = new TableRow();
tc = new TableCell();
tc.Style["padding-top"] = "7px";
tc.VerticalAlign = VerticalAlign.Top;
Label lblEmailAddress = new Label();
lblEmailAddress.Text = "Email Address:";
tc.Controls.Add(lblEmailAddress);
tr.Controls.Add(tc);

// Email Address textbox
tc = new TableCell();
tc.VerticalAlign = VerticalAlign.Top;
txtEmailAddress = new TextBox();
txtEmailAddress.ID = "txtEmailAddress";
txtEmailAddress.Width = Unit.Pixel(300);
tc.Controls.Add(txtEmailAddress);
tr.Controls.Add(tc);

t.Controls.Add(tr);

// Phone Number label
tr = new TableRow();
tc = new TableCell();
tc.Style["padding-top"] = "7px";
tc.VerticalAlign = VerticalAlign.Top;
Label lblPhone = new Label();
lblPhone.Text = "Phone Number:";
tc.Controls.Add(lblPhone);
tr.Controls.Add(tc);

// Phone Number textbox
tc = new TableCell();
tc.VerticalAlign = VerticalAlign.Top;
txtPhone = new TextBox();
txtPhone.ID = "txtPhone";
txtPhone.Width = Unit.Pixel(300);
tc.Controls.Add(txtPhone);
tr.Controls.Add(tc);

t.Controls.Add(tr);

// Message label
tr = new TableRow();
tc = new TableCell();
tc.Style["padding-top"] = "7px";
tc.VerticalAlign = VerticalAlign.Top;
Label lblMessage = new Label();
lblMessage.Text = "Message:";
tc.Controls.Add(lblMessage);
tr.Controls.Add(tc);

// Message textbox
tc = new TableCell();
tc.VerticalAlign = VerticalAlign.Top;
txtMessage = new TextBox();
txtMessage.ID = "txtMessage";
txtMessage.Height = Unit.Pixel(100);
txtMessage.Width = Unit.Pixel(400);
txtMessage.TextMode = TextBoxMode.MultiLine;
txtMessage.Wrap = true;
tc.Controls.Add(txtMessage);
tr.Controls.Add(tc);

t.Controls.Add(tr);

// Empty table cell
tr = new TableRow();
tc = new TableCell();
tr.Controls.Add(tc);

// Label for telling the user the message was sent
tc = new TableCell();
tc.VerticalAlign = VerticalAlign.Top;
lblMessageSent = new Label();
lblMessageSent.Text = "Your message has been sent. Thank you.";
lblMessageSent.Font.Bold = true;
lblMessageSent.Visible = false;
tc.Controls.Add(lblMessageSent);
tr.Controls.Add(tc);

t.Controls.Add(tr);

// Empty table cell
tr = new TableRow();
tc = new TableCell();
tr.Controls.Add(tc);

// Send Message button
tc = new TableCell();
btnSendMessage = new Button();
btnSendMessage.Text = "Send Message";
btnSendMessage.Click += new EventHandler(btnSendMessage_Click);
tc.Controls.Add(btnSendMessage);
tr.Controls.Add(tc);

t.Controls.Add(tr);

this.Controls.Add(t);
}

Finally, we need to add an event handler to send the message as an email when the Send Message button is clicked by the user. In the code above, the event handler was already wired up with the line btnSendMessage.Click += new EventHandler btnSendMessage_Click);, so now we just need to create the btnSendMessage_Click function. This function simply builds an email message using text that was entered into the text boxes, and sends the email using SharePoint's SPUtility.SendEmail() function.

You will need to change the "to" and "from" fields in the message header for your specific situation. The "to" field specifies where the email will be sent, and the "from" field is the email address that the email should appear to be from. The "from" field isn't too important, but some mail servers may require this to be a valid email address.


protected void btnSendMessage_Click(object sender, EventArgs e)
{
// Build the email subject string
System.Text.StringBuilder subject = new System.Text.StringBuilder();
subject.Append("Contact Form Message from ");
subject.Append(txtContactName.Text);

// Build the email message string
System.Text.StringBuilder message = new System.Text.StringBuilder();
message.Append("Contact Name: ");
message.AppendLine(txtContactName.Text);
message.Append("Email Address: ");
message.AppendLine(txtEmailAddress.Text);
message.Append("Phone: ");
message.AppendLine(txtPhone.Text);
message.AppendLine();
message.AppendLine("Message:");
message.AppendLine(txtMessage.Text);

// Construct the message header
System.Collections.Specialized.StringDictionary messageHeader =
new System.Collections.Specialized.StringDictionary();
messageHeader.Add("to", "CustomerService@example.com"); // TODO: Where to send the email
messageHeader.Add("from", "ContactForm@example.com"); // TODO: Who the email should be "from"
messageHeader.Add("subject", subject.ToString());
messageHeader.Add("content-type", "text/plain");

// Send the email
Microsoft.SharePoint.Utilities.SPUtility.SendEmail(
SPContext.Current.Web, messageHeader, message.ToString());

// Let the user know the message was sent
lblMessageSent.Visible = true;

// Clear out the input fields
txtContactName.Text = "";
txtEmailAddress.Text = "";
txtPhone.Text = "";
txtMessage.Text = "";
}

Testing the Web Part
Now we are ready to test the web part. The easiest way to do this is to choose Deploy Solution from the Build menu in Visual Studio 2008. After it has built and deployed successfully, open a web browser and navigate to the SharePoint website. From the Site Actions menu, choose Edit Page. This will place the page into Edit Mode, where web parts can be added, removed, and configured.

For testing purposes, we don't care about the exact placement of the web part, so just click Add a Web Part in the main left zone. This will open up a Dialog box listing all of the web parts that are available for use on this SharePoint server. If you scroll down the list, you should see the ContactForm web part. Put a checkbox next to this web part and click the Add button.



You should now see the contact form displayed on the page. While still in Edit Mode, you can change other settings such as the title that is displayed above the web part, or the height and width. For testing we are going to leave everything as the default, so just click the Exit Edit Mode button. The page will now show the contact form and we are ready to test it. Enter a name, email address, phone number, and message, and click Send Message. If all is successful, you will see a message saying your message has been sent and within a few minutes receive the email that was generated by btnSendMessage_Click().



Checking the Outgoing E-Mail Settings
If your receive an error message when you click Send Message or if the email does not arrive within 5 or 10 minutes, it could be that the outgoing email settings have not been configured in SharePoint. This can be done by a SharePoint administrator using the Central Administration website. In Central Administration, go to the Operations tab and select Outgoing E-Mail Settings. Make sure the Outbound SMTP Server is configured with the name of the mail server.



Deploying the Web Part
Once you have tested the web part, it is ready to be deployed as a solution to the production SharePoint server. For this we will create a SharePoint solution package, which is a .cab file that has a .wsp extension. The .wsp file is created automatically when you choose Deploy from within Visual studio. Change the active configuration in Visual Studio from Debug to Release, and then choose Deploy Solution from the Build menu.

After it has successfully deployed the release version to your local SharePoint server, there will be a file called ContactFormWebPart.wsp in the /bin/Release subfolder of your project directory. Copy this file to a folder on your production SharePoint web server, or to a location that can be accessed from this server. Then, run the following commands from a command prompt on the production SharePoint web server. These commands will add the solution to SharePoint and then deploy the solution, making it available for use by all sites.


C:\>stsadm -o addsolution -filename ContactFormWebPart.wsp


C:\>stsadm -o deploysolution -name ContactFormWebPart.wsp -immediate -allowgacdeployment -allcontenturls

Now the web part is available for use on the production SharePoint server. Only one more thing is left to do. When you want to use it in a SharePoint site, you will need to add it to that site's web part gallery. To do this, navigate to your SharePoint site and go to Site Actions - Site Settings. Then clicking on the Web Parts link under the Galleries section. This opens up a web page listing the web parts that are currently available for this site. Click New to add a new web part to the list. The next web page shows the deployed web parts. Check the box next to ContactFormWebPart.ContactForm and then click the Populate Gallery button.

You should now see the Contact Form Web Part in the list of web parts in this site's gallery. Once the web part is in the gallery, you can edit a page in the site, and add the web part to the page, just as we did during testing.

Additional Improvements
There are some improvements that can be made to the Contact Form Web Part that we've created, but these are beyond the scope of this article. Here are some ideas for improving the Contact Form Web Part:

First, we could add validation to the fields to make sure that the required fields are filled in and that the data entered matches the expected format. For example, contact Name should be required, Message should be required, the email address should match the typical format of an email address, and the phone number should be in the format of a valid phone number.

Second, we could add properties to the web part to allow customization of the label text and the to and from addresses used for sending the email. These properties would allow changes to be made to the web part's appearance while editing the page in SharePoint instead of requiring those changes to be made in the source code.

Other Thoughts
Web parts can be created using Visual Studio 2005, but Visual Studio 2008 in conjunction with the downloadable extensions for WSS 3.0 make packaging and deploying your web part much easier. I highly recommend using Visual Studio 2008 for web part development if possible.

In order to use the WSS extensions for Visual Studio 2008, the development environment needs to run on a SharePoint server. But many developers use a client operating system for their development instead of a server operating system, which is required by SharePoint. This is where Microsoft Virtual PC can really be helpful. Virtual PC will allow you to run another computer instance virtually, on your development PC, so you can create a Virtual PC image for your SharePoint web part development environment.

If you are new to web part development and want to try it out without the work of setting up a full SharePoint environment, Microsoft provides a Windows SharePoint Services 3.0 SP1 Developer Evaluation VPC Image that has WSS 3.0, Visual Studio, and the extensions already installed. You can use this with Virtual PC for an "instant" SharePoint environment.

Conclusion
In this article you learned how to create a simple web part for SharePoint that implements a contact form that collects information and sends it as an email to a recipient. There are many more possibilities for the use of web parts, including communicating with other web parts in SharePoint and integrating with external databases and applications. The ability of SharePoint to use custom web parts is a powerful feature that can be used to extend the functionality of SharePoint beyond what is possible with basic customization.