Back to previous

Useful common methods for Sharepoint Development

Time and time again, I use these methods in coding for Sharepoint. These include methods for querying a list, bind a Dropdown list to a list, and bind a Dropdown list or a Checkbox list to a multiple choice field. They just save me tons of times.

public static SPListItemCollection queryList(string strFilterName, string strFilterValue, 
             string strFilterType, SPList spList)
        {
            SPQuery query = new SPQuery();
            query.Query = "<Where><Eq><FieldRef Name='" + strFilterName + "' /><Value Type='" + strFilterType + "'>" + strFilterValue + "</Value></Eq></Where>";
            return spList.GetItems(query);
        } public static void bindLookupList(DropDownList ddl, SPList spList, SPListItemCollection result, string strTextField, string strValueField, string strOrderByFieldName)
        {
            SPQuery query = new SPQuery();
            query.Query = "<OrderBy><FieldRef Name=\"" + strOrderByFieldName + "\" /></OrderBy>";
           
            if (spList != null)
                ddl.DataSource = spList.GetItems(query);
            else if (result != null)
                ddl.DataSource = result;
            ddl.DataTextField = strTextField;
            ddl.DataValueField = strValueField;
            ddl.DataBind();
            ddl.Items.Insert(0, new ListItem("Please Select", ""));
        } public static void bindMultiChoices(Control ctr, SPList oList, string strFieldName, string strDefaultText, string strDefaultValue)
        {
            DropDownList dll = new DropDownList();
            CheckBoxList cbl = new CheckBoxList();
           
            if (ctr.GetType() == typeof(DropDownList))
            {
                dll = (DropDownList)ctr;
                SPFieldChoice field = (SPFieldChoice)oList.Fields[strFieldName]; foreach (string str in field.Choices)
                {
                    dll.Items.Add(new ListItem(str, str));
                }
                if (string.IsNullOrEmpty(strDefaultText))
                    strDefaultText = "Please Select";
                if (string.IsNullOrEmpty(strDefaultValue))
                    strDefaultValue = ""; dll.Items.Insert(0, new ListItem(strDefaultText, strDefaultValue));
            }
            else if (ctr.GetType() == typeof(CheckBoxList))
            {
                cbl = (CheckBoxList)ctr;
                SPFieldMultiChoice choices = (SPFieldMultiChoice)oList.Fields[strFieldName]; foreach (string str in choices.Choices)
                {
                    cbl.Items.Add(new ListItem(str, str));
                } }
           
        }

 

ShareThis

If you think this post is useful, please recommend me at the bottom of the page. ;)

Discussion