Friday 18 January 2008

MOSS 2007 Webparts

After much searching and hitting my head on the desk I got the following to work: I was looking at getting a drop down on a web page, for our public facing MOSS site, that has a list of items from a list. Here is the code (there is still an issue if I create another WP, pointing to a different list, and add it to the page - it raises a DISP_E_EXCEPTION)

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Runtime.InteropServices;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;

namespace ListMenu
{
[XmlRoot(Namespace="ListMenu")]
[Guid("F10D314C-6CFF-4098-BF03-4F763099B0A5")]
[ToolboxData("<{0}:LocationDetail runat=server>")]
public class ListMenuLocation : Microsoft.SharePoint.WebPartPages.WebPart
{
private DataTable tblLocation;
///
/// Set the Export Type, Chrome State/Type of the Web Part
///

public ListMenuLocation()
{
this.ExportMode = WebPartExportMode.NonSensitiveData;
this.ChromeState = PartChromeState.Normal;
this.ChromeType = PartChromeType.None;
}
///
/// Populate the DataTable with the publicly visible location
///

private void PopulateDataTable()
{
try
{
tblLocation = new DataTable();
using (SPSite spSite = SPContext.Current.Site)
{
SPList spList = spSite.AllWebs[0].Lists["Locations"];
SPQuery oQuery = new SPQuery();
...

SPListItemCollection spLIC = spList.GetItems(oQuery);
tblLocation = spLIC.GetDataTable();
}
}
catch (SPException ex)
{ throw ex; }
catch (Exception ex)
{ throw ex; }
}
protected override void CreateChildControls()
{
try
{
PopulateDataTable();
CreateDropDown();
base.CreateChildControls();
}
catch(Exception ex)
{
System.Web.UI.WebControls.TextBox message = new TextBox();
this.Controls.Add(message);
message.Visible = false;
message.Text = ex.Message.ToString();
}
}
///
/// Create and Populate the drop down
///

private void CreateDropDown()
{
System.Web.UI.WebControls.DropDownList ddlLocation = new DropDownList();
ddlLocation.ID = "LocationDropDown";
ddlLocation.DataSource = tblLocation;
ddlLocation.DataTextField = "Title";
ddlLocation.DataValueField = "TabID";
ddlLocation.DataBind();
ddlLocation.Items.Insert(0, new ListItem("Please select...", "0"));
ddlLocation.SelectedIndexChanged += new EventHandler(ddlLocation_SelectedIndexChanged);
this.Controls.Add(ddlLocation);
}
void ddlLocation_SelectedIndexChanged(object sender, EventArgs e)
{
...

WriteOutURL(redirectTo);
}
///
/// Write out the location for the redirect to a text box.
///

/// string: Redirect URL
private void WriteOutURL(string url)
{
...

}
}
}

No comments: