Quantcast
Channel: Development With A Dot
Viewing all articles
Browse latest Browse all 404

TextBox With Suggestions in SharePoint

$
0
0

This control will suggest values for a text box from the values in a SharePoint list. It makes use of the HTML5 datalist element in a slightly customized TextBox control.

   1:publicclass SPTextBox : TextBox
   2: {
   3:public SPTextBox()
   4:     {
   5:this.FieldName = "Title";
   6:     }
   7:  
   8:     [Description("List name")]
   9:     [DefaultValue("")]
  10:public String ListName
  11:     {
  12:         get;
  13:         set;
  14:     }
  15:  
  16:     [Description("Field name")]
  17:     [DefaultValue("Title")]
  18:public String FieldName
  19:     {
  20:         get;
  21:         set;
  22:     }
  23:  
  24:protectedoverridevoid Render(HtmlTextWriter writer)
  25:     {
  26:         var addList = (this.Visible == true) && (String.IsNullOrWhiteSpace(this.ListName) == false) && (String.IsNullOrWhiteSpace(this.FieldName) == false);
  27:         var dataId = String.Concat(this.ID, "_data");
  28:  
  29:if (addList == true)
  30:         {
  31:this.Attributes["list"] = dataId;
  32:         }
  33:  
  34:base.Render(writer);
  35:  
  36:if (addList == true)
  37:         {
  38:             var list = SPContext.Current.Web.Lists[this.ListName];
  39:             var values = list.Items.OfType<SPListItem>().Select(x => x[this.FieldName]).Distinct().OrderBy(x => x.ToString());
  40:  
  41:             writer.WriteLine(String.Format("<datalist id=\"{0}\">", dataId));
  42:  
  43:foreach (var valuein values)
  44:             {
  45:                 writer.WriteLine(String.Format("<option value=\"{0}\"/>", value));
  46:             }
  47:  
  48:             writer.WriteLine("</datalist>");
  49:         }
  50:     }
  51: }

Before you ask, yes, I know about GetDistinctFieldValues, but it is marked as deprecated, which means it may go away in a future version of SharePoint and besides it can’t get distinct values for all fields – Title, for instance.

You declare it as a regular TextBox, plus a ListName and a FieldName properties:

   1:<my:SPTextBoxrunat="server"ID="something"ListName="Tasks"FieldName="Title"/>

And when it runs, it will present something like this:

image


Viewing all articles
Browse latest Browse all 404

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>