Bilbro Bloggins

Musings of Brian Bilbro

Dropdown Filter Web Part in SharePoint – Part Two

This is the second part of a multipart blog series.

  1. In part one, we created a simple SharePoint Web Part which displayed a text label that could be set via the Web Part Properties Editor.
  2. In part two of this blog series, we extended the simple SharePoint Web Part by adding a dropdown list box and populating it with values from a SharePoint list.
  3. In part three, we add the capabilities to use the selected value in the dropdown list box to filter various SharePoint lists on the page.
  4. In part four, you can download the Visual Studio 2008 project solution.

Blog Series Summary:

As a part of a proof of concept site I was creating in SharePoint, I wanted to learn how to create a web part in SharePoint that can communicate to other web parts on the page.  The web part that I wanted to create was a drop-down list box that would display a list of projects.   Selecting a project on the drop-down list would then drive the contents of the various SharePoint project lists (issues, notes, risks, etc…) on the SharePoint page.

Part Two:

In part two of this blog, we’ll extend the simple SharePoint Web Part by adding a dropdown list box and populating it with values from a SharePoint list.

Step 1 – After opening the Web Part project, we’ll need to add the necessary code to the CreateChildControls method to create an instance of the dropdown list box.

private DropDownList _sourceDropDownList = null;
protected override void CreateChildControls()
{
    base.CreateChildControls();
    _textLabel = new Label();
    this.Controls.Add(_textLabel);
    _sourceDropDownList = new DropDownList();
    _sourceDropDownList.AutoPostBack = true;
    this.Controls.Add(_sourceDropDownList);
}

The AutoPostBack property is used later on in part three of this blog series.

Step 1 – Add properties to keep track of the name of the source SharePoint list (SourceListName), the SharePoint list itself (SourceList), the field in the list to use as the display text in the dropdown list box (DisplayTextField) and the field in the list to use as the value option in the dropdown list box (ValueField).

private SPList _sourceList = null;
private string _sourceListName = null;
private string _displayTextField = null;
private string _valueField = null;
private SPList SourceList
{
    get
    {
        if ((_sourceList == null) && (this.SourceListName != null))
        {
            try
            {
                _sourceList = SPContext.Current.Web.Lists[SourceListName];
            }
            catch
            {
                // TODO: Insert your custom error handling here
            }
        }
        return _sourceList;
    }
}
[WebBrowsable(true),
Personalizable(PersonalizationScope.User),
WebDescription("Source List Name"),
Category("Dropdown Filter"),
WebDisplayName("List Name")]
public string SourceListName
{
    get { return _sourceListName; }
    set { _sourceListName = value; }
}
[WebBrowsable(true),
Personalizable(PersonalizationScope.User),
WebDescription("Display Text Field"),
Category("Dropdown Filter"),
WebDisplayName("Display Text Field")]
public string DisplayTextField
{
    get { return _displayTextField; }
    set { _displayTextField = value; }
}
[WebBrowsable(true),
Personalizable(PersonalizationScope.User),
WebDescription("Value Field"),
Category("Dropdown Filter"),
WebDisplayName("Value Field")]
public string ValueField
{
    get
    {
        string returnValue = String.Empty;
        if ((_valueField != null) && (_valueField.Length > 0))
        {
            returnValue = _valueField;
        }
        else
        {
            if (this.SourceList != null)
            {
                DataTable dataTable = this.SourceList.Items.GetDataTable();
                if ((dataTable != null) && (dataTable.Columns.Count > 0))
                {
                    returnValue = dataTable.Columns[0].ColumnName;
                }
            }
        }
        return returnValue;
    }
    set { _valueField = value; }
}

A few items of note for these properties

SourceList - Sadly, there is not an Exists or Contains method on the Lists collection.  The only way to determine if the list exists is to either catch the exception or loop through the collection and check each name. See http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/088fe9ad-8db2-4c0e-8518-1235122e0d6e/

ValueField – If _valueField is currently not set then the control will use the first field listed for the SharePoint list.

using statements needs – The DataTable reference will require the following to be added to your list of using statements at the top of the class.  You will also need to add a project reference for System.Data.

using System.Data;

 

Step 3 – Override the OnLoad method and populate your dropdown list box with the values from the SharePoint list.

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    LoadData();
}
private void LoadData()
{
    if (this.Page.IsPostBack == false)
    {
        if ((SourceList != null) && (SourceList.Items != null))
        {
            for (int i = 0; i < SourceList.Items.Count; i++)
            {
                SPListItem item = SourceList.Items[i];
                ListItem listItem = new ListItem();
                if (this.DisplayTextField != null && this.DisplayTextField.Length > 0)
                {
                    listItem.Text = item[this.DisplayTextField].ToString();
                }
                else
                {
                    listItem.Text = item[0].ToString();
                }
                if (this.ValueField != null && this.ValueField.Length > 0)
                {
                    listItem.Value = item[this.ValueField].ToString();
                }
                else
                {
                    listItem.Value = item[0].ToString();
                }
                _sourceDropDownList.Items.Add(listItem);
            }
        }
    }
}

I originally has the dropdown list box populated with this code:

_sourceDropDownList.DataSource = SourceList.Items;
if (this.DisplayTextField != null && this.DisplayTextField.Length > 0)
{
    _sourceDropDownList.DataTextField = this.DisplayTextField;
}
if (this.ValueField != null && this.ValueField.Length > 0)
{
    _sourceDropDownList.DataValueField = this.ValueField;
}
_sourceDropDownList.DataBind();

For some reason this method of binding SharePoint Lists to a control didn't work very well.  If the bound fields were Title or Name it worked well.  If it was some other field than it was not able to find the column.  Instead I've gone to a manual looping of the data.

 

Step 4 – And finally, we’ll want to make sure the child controls (label and dropdown list box) are created no later than the init phase of the control’s lifecycle.   If you do not add EnsureChildControls then it’s possible to get an Object Reference Not Set To An Instance Of An Object error when your LoadData method is fired because the dropdown list box might not be created yet.

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    EnsureChildControls();
}

 

Step 5 – If you have not done so, set the URL to your SharePoint server:  Right click project -> Properties -> Debug -> Start browser with URL.

Step07.a.WebPartProperties 

Step07.b.DebugURL

Step 6 – Build and Deploy the web part to your SharePoint server. Right click project -> Deploy

Step08.b.Deploy

Step 7 – If you already have a page with your web part deployed then edit that page.  Otherwise, add your web part to a page and edit your web part properties.  You’ll need to reference a SharePoint list that already exists on the site for the List Name property.

Step06.ModifyProperties

Step 8 – If the SharePoint list name is correct and you’ve specified valid Display Text Field and Value Field then your SharePoint web part should look something like this:

Step08.Results

 

That completes part two of the SharePoint Dropdown Filter Web Part Series.  Continue on to Part Three to see how to implement the filter provider capabilities.

» Similar Posts

  1. Dropdown List Box Filter Web Part in SharePoint – Part One
  2. Dropdown Filter Web Part in SharePoint – Part Three
  3. Creating a Lookup List for SharePoint with VSeWSS

» Trackbacks & Pingbacks

    No trackbacks yet.
Trackback link for this post:
http://bilbrobloggins.com/trackback.ashx?id=8
 

» Comments

  1. Jack avatar

    Hi Brian,

    Thanks a lot for posting such a detailed instructions for creating web part! It helps a lot.

    I have one question/issue:

    After user changes selection in the dropdownlist, web part refresh happens as AutoPostBack is set to true.

    So, what actually happens is - the following methods are called:

    OnInit and then OnLoad.

    So, it looks like all the controls are created again, but as Page.IsPostBack is true, the dropdownlist Items are not populated.

    So, basically, after changing selection dropdownlist become empty in my case.

    I am pretty sure I am missing something quite important, but I can't figure out what it is.

    Thanks!

    Jack

    (just to make it clear - I am new to sharepoint/web/asp.net development)

    Jack — January 29, 2010 6:35 AM
  2. Sandeep avatar

    Very nice series, you saved me lot of time. I have made some more changes to avoid extra checks and performance related changes and I will post it on my blog soon. Will leave you a message here that time.. thanks again

    Sandeep — February 18, 2010 6:52 AM
  3. Valentin avatar

    Nice Article!

    When the display textfield is left blank you'll get an error. This happens in this section.

    [code]

    if (this.DisplayTextField != null && this.DisplayTextField.Length > 0)

    {

    listItem.Text = item[this.DisplayTextField].ToString();

    }

    else

    {

    listItem.Text = item[0].ToString();

    }

    [/code]

    If you want to get rid of it, do the following.

    [code]

    if (this.DisplayTextField != null && this.DisplayTextField.Length > 0)

    {

    listItem.Text = item[this.DisplayTextField].ToString();

    }

    if (this.DisplayTextField != null && this.DisplayTextField.Length <= 0)

    {

    listItem.Text = item["Title"].ToString();

    }

    else

    {

    listItem.Text = item[_displayTextField].ToString();

    }

    [/code]

    Thanks!

    Valentin — March 22, 2010 9:27 AM
  4. Quang phi avatar

    Hi Brian, I copied your code and try to run the steps you guidance but choose not to filter out results, your code is missing anything?

    would you respond to me

    I thank you

    Quang phi — March 23, 2010 11:33 PM
  5. Steve H avatar

    Hi,

    If I use wspbuilder to make a wsp and then stsadm to install solution it says operation successfull. Using CA to deply work ok too...but it is not available as a web part to use on my site.

    There are no features listed to activate..

    ?

    Any ideas?

    Thanks,

    Steve

    Steve H — February 21, 2011 5:20 AM
  6. Pavel avatar

    Hi! I'm newbie in SP development. And all I want to say about this article, it's really great!

    Thank you

    Pavel — May 25, 2011 6:28 AM

» Leave a Comment