Creating Visual Web Parts for Sharepoint 2010 using Visual Studio 2010 – Part 2

Shameem Ahmed 7 February 2012 0




This is in continuation of Creating Visual Web Parts for Sharepoint 2010 using Visual Studio 2010  – Part 1
In this article we will expand the functionality of the project and add the following functions:

1. Fetch Fields of a selected sharepoint list.

2. Populating Fields into a list box and let the user select the fields.

Its recommended to check the previous article before continuing. Click on the below link to read Part 1
article:

http://techwirenews.com/creating-visual-web-parts-for-sharepoint-2010-using-visual-studio-2010-%e2%80%93-part-1-2/

Solution

Open the project created in Part 1 article.

Add the following code to SelectedIndexChanged event of lbLists control.

protected void lbLists_SelectedIndexChanged(object sender, EventArgs e)
{
            if (lbLists.SelectedIndex < 0)
                   return;

            SPWeb web = SPContext.Current.Web;
            SPList list = web.Lists[lbLists.SelectedIndex];

             lbFields.Items.Clear();
             foreach (SPField field in list.Fields)
            {
                        lbFields.Items.Add(new ListItem(field.Title, field.Id.ToString()));
            }
 }

The entire code should look like this:

using System;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

 using Microsoft.SharePoint;

 namespace VisualWebPartProject1.vwpList

{

    public partial class vwpListUserControl : UserControl

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            SPWeb web = SPContext.Current.Web;

             lbLists.Items.Clear();

             foreach (SPList list in web.Lists)

            {

                lbLists.Items.Add(new ListItem(list.Title, list.ID.ToString()));

            }

        }

         protected void lbLists_SelectedIndexChanged(object sender, EventArgs e)

        {

             if (lbLists.SelectedIndex < 0)

                return;

             SPWeb web = SPContext.Current.Web;

             SPList list = web.Lists[lbLists.SelectedIndex];

             lbFields.Items.Clear();

             foreach (SPField field in list.Fields)

            {

                lbFields.Items.Add(new ListItem(field.Title, field.Id.ToString()));

            }

         }

    }

}

Deploy the project and by pressing F5

Insert the web part into sharepoint page by doing the following:

Select Edit to edit the sharepoint page.

Goto Insert tab and click Web Part

Select Custom from Categories and web part name Web Parts section

Click Add to insert our new web part into the page.

Summary

In this article we expanded our web part control to select a sharepoint list and select fields from the selected list. In the coming article we will continue to expand the project .

 

 

 

 




Shameem Ahmed (370 Posts)

Leave A Response »