Tuesday, June 26, 2007

Developing and Using Web User Control in Web Parts in MOSS 2007


1) Open a new ASP.Net Web Site and name it appropriately.



2) Add a Web User Control file and name it appropriately.



3) Design and create controls according to your need in ascx file.



4) Write the code at button click events as per your requirements.



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class UserEntry : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string strName = txtFirstName.Text + " " + txtLastName.Text;
string strAddress = txtCity.Text + ", " + ddlState.SelectedItem.Text + ", " + txtCountry.Text;

lblResName.Text = strName;
lblResAddress.Text = strAddress;
}
protected void btnReset_Click(object sender, EventArgs e)
{
txtFirstName.Text = "";
txtLastName.Text = "";
txtCity.Text = "";
ddlState.SelectedIndex = 0;
txtCountry.Text = "";
}
}





5) Copy your both ascx and ascx.cs file in following path:

C:\Inetpub\wwwroot\wss\VirtualDirectories\80\UserControls

If UserControls folder is not present then create it.

6) Now open a new Web Control Library project and name it appropriately. Add reference of Microsoft.SharePoint.dll in your project. It is present at following path:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\ISAPI\Microsoft.SharePoint.dll



7) Open a Web Custom Control and name it properly.



8) Inherit Web Part class from System.Web.UI.WebControls.WebParts.WebPart.
Override the CreateChildControls method to load the previously created ascx Web Control.



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

namespace UserControl
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:SPUserControlWP runat=server></{0}:SPUserControlWP>")]
public class SPUserControlWP : WebPart
{
private Control _control;

protected override void CreateChildControls()
{
_control = this.Page.LoadControl(@"~/usercontrols/UserEntry.ascx");
this.Controls.Add(_control);
}
}
}



9) Create Strong-Name for project and build it.

10) Write following codes in your site web.config (i.e. C:\Inetpub\wwwroot\wss\VirtualDirectories\80\web.config) file.



<SafeControls>
<SafeControl Assembly="UserControl, Version=1.0.2721.26545,
Culture=neutral, PublicKeyToken=1af8fa800ec59b02"
Namespace="UserControl" TypeName="*" Safe="True" />
</SafeControls>




<assemblies>
<add assembly="UserControl, Version=1.0.2721.26545,
Culture=neutral, PublicKeyToken=1af8fa800ec59b02" />
</assemblies>



Note: For details regarding way to create strong name and copy version and PublicTokenKey, refer my earlier post.

11) Create webpart file for Web Part.



<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
<type name="UserControl.SPUserControlWP" />
<importErrorMessage>
Cannot import this Web Part.
</importErrorMessage>
</metaData>
<data>
<properties>
<property name="Title" type="string">
UserControl Web Part
</property>
<property name="Description" type="string">
A
demonstration using UserControl in a SharePoint
WebPart
</property>
</properties>
</data>
</webPart>
</webParts>



12) Add the above created *.webpart xml file to your site.


Note: For details regarding the way to add Web Part, please refer my earlier post --- Developing Custom Web Part.


Suggested Link:

1) WebParticles: Developing and Using Web User Controls as WebParts in Microsoft Office SharePoint Server 2007
http://www.codeproject.com/spoint/WebParticles.asp

10 comments:

Anonymous said...

Hi everybody,
I am developing one business application using MOSS.
I am having two options for storing business data:
1) MOSS custom list
2) SQL server 2005 tables

If I use MOSS custom list,it will break data integrity of business data tables as I can not use Primary key and foreign key relationship on custom list.

If I use SQL server 2005 tables for storing business data,I can not use in build MOSS functionality like Work flows,custom list etc.


Is there any other better way of doig this?

Thanks in advance.

Avinash said...

Hi Amit,

Try to use MOSS's BDC. I think in that scenario you can preserve the relationships between your tables.

~ Avi

Anonymous said...

Hi Avi,
I read your blog and I gained a lot from it. I could use it in my application but the thing is, the values in the dropdown that I would be using will be coming from distinct column values in one of my custom lists. How would I do this?

To give you a background, and might as well ask for your help,
I have an application, with controls:
- Role dropdownlist (values from roles/groups from my site)
- User dropdown (values from distinct user from a list in my site)
- on select of Role, the User dropdown would be trimmed down to Users of that particular role only.
- then after I selected both Role and User dropdown, the gridview will display the result, records have a checkbox beside them
- I could choose any record from the list
- AD Picker
- OK button (on click event, Those users under the role that I choose would be replaced with the new user I selected from the AD picker -- these changes would reflect on the custom list where I got the roles/users value)

Do you have any idea on how to do this?

Thanks a lot!!

Avinash said...

Hi Jake,


There are two approaches to accomplish the required task:
1) Use a custom web part directly, in that create the control and do all logic in it.
2) Use a custom control and refer that control via a web part.


If we go with first approach, then first we will create all the desired control in the custom web part’s class. First create a table (HTML Table/C# Table) control for better UI and layout (for e.g., named tableMain). First column of table will contains the label for the dropdown and second column contains the actual dropdown control.

In the 1rst row and 2nd column of table, add an instance of Dropdown control (e.g. named ddlRoles).
In the 2nd row and 2nd column of table, add another instance of Dropdown control (e.g. named ddlUsers).
In the 3rd row (with column span 2) of table, add an instance of GridView control (e.g. named grdView).

Do all the above activities in CreateChildControls() event of Custom web part class. Refer following article Developing Custom Web Part regarding creating a custom web part.


Now use the share point object model to do following operations with SharePoint’s list.
1) In the CreateChildControl event, add code to populate the Roles’s dropdown (ddlRoles).
2) In the dropdown event of ddlRoles, add the code to populate the Users’s dropdown.
3) In the dropdown event of ddlUsers, display the Gridview’s data.
4) Now do all the operation with Gridview.
5) On Ok button event, get the instance of Users’s list. Add/delete/edit, the Users list as per your logic. Then again call the dropdown event of ddlRoles (by code, without doing the click operation in dropdown).



Refer following links just for guidance:
1) How to: Add or Delete List Items
2) SPListItem Class


You can search operation related to SPList and SPListItem in google.



The second approach is similar to first, but here in ascx control we do all the UI and logic related work.


Please correct me, if I misunderstood your requirements or I am wrong/miss somewhere.

Thanks and Regards,
Avi

Anonymous said...

Hi Avi!

Your suggestions are all helpful especially if I'm trying to build my code using the first option.

To tell you frankly, I am no fan of C# for I was more exposed in VB and I am more comfortable building a page using ASP.NET Web App, which in this case I think is what you are suggesting as a second option.

Further, could you give me details on how to do this?
I could do the designing of the ascx, but could you give me points on how to populate those dropdown based on column values in another list. also on how to deploy them and use them in my moss site?

Many thanks!

Unknown said...

Hello Avinash,
Can you please tell me how to deploy infopath form using XML Form view.
I have written following code in Web Control Library:
private Control _control;
protected override void CreateChildControls()
{
_control = this.Page.LoadControl(@"~/UserControls/WebUserControl.ascx");
this.Controls.Add(_control);
}

I have included XML Form view in User control and specified XSN location from formtemplate library.

When I uploaded web part in sharepoint site, it is showing me blank.

Does anyone know solution for this ?

Developer said...

Hi
Avinash, your post is helpful to us , but we have a doubt...you said '11.Create webpart file for Web Part'. and Add create webpart file ' where to do these two steps. can you pls clearify.

thanks and regards
Ganesh

Avinash said...

Hi Ganesh,

1) "11) Create webpart file for Web Part" --- means create xml file with extension *.webpart.

2) "12) Add the above create webpart file in your site." --- add the *.webpart xml file to your site.

To know in details the steps required to add *.webpart file, please refer the following post :
Developing Custom Web Part

Anonymous said...

Hey Avinash,

I am trying to do exactly what you have done but it is not working for me.

I have 3 dropdown controls in my user control country,state,city and if i change country then state should change and similarly city. All this code is already written in my UserControl. I have tested this control in aspx page and it is working fine.

Now when I load this control in WebPart I have written below code.

public class WebPart2:WebPart
{
[WebBrowsable(true)]
[WebDescription("User Control Path")]
[WebDisplayName("User Control Name")]
[Category("Custom Properties")]
[Personalizable(PersonalizationScope.User)]
public string UserControlPath { get; set; }

[WebBrowsable(true)]
[WebDisplayName("Display All Lists")]
[WebDescription("Display All Lists")]
[Category("Custom Properties")]
[Personalizable(PersonalizationScope.User)]
public string SiteURL { get; set; }


private TestUC control;

protected override void CreateChildControls()
{
TestUC control = (TestUC)Page.LoadControl(UserControlPath);
control.SiteURL = SiteURL;
Controls.Add(control);
}


}

Whenever I change the country dropdown it always gets this control and add it to the Controls collection. My postback events are never firing. Do you know what I am doing wrong?

Thanks,
MS

Avinash said...

Hi MS,

Set autopostback property of dropdown to true.

Sample code:

<asp:DropDownList ID="MyDropDownList" runat="server" OnSelectedIndexChanged="MyDropDownList_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>

Google