/// <Summary> /// Add a field /// </summary> /// <param name = "fields"> set of added fields </param> // /<param name = "fieldDisplayName"> Field name </param> // <param name = "fieldType"> Field Type </param> // <param name =" defaultVal "> default value </param> /// <param name =" hidden "> hide </param> /// <param name =" allowdeletion "> whether to allow deletion </param> // <returns> </returns> public void CreateField (SPFieldCollection fields, string fieldDisplayName, SPField Type fieldType, string defaultVal, bool hidden, bool allowdeletion) {if (fieldDisplayName = null) throw new ArgumentNullException ("fieldDisplayName "); // determine whether the field bool isExists = fields already exists. containsField (fieldDisplayName); // if a field exists, if (isExists) return is not created; // false indicates that the value can be blank fields. add (fieldDisplayName, fieldType, false); SPField field = new SPField (fields, fieldDisplayName) {AllowDeletion = allowde Letion, DefaultValue = defaultVal}; // remember to call Update (); Method field. update ();} protected void create field _ Click (object sender, EventArgs e) {using (SPSite site = new SPSite (siteUrl) {using (SPWeb web = site. rootWeb) {SPList list = web. lists ["KB"]; web. allowUnsafeUpdates = true; // remember to set this attribute! CreateField (list. Fields, "MyTestAdd", SPFieldType. Text, "Test", false, false );}}}
Of course, the above Code simply implements adding fields, but if the field type is SPFieldType. when using User, defaultVal must write the User name in AD. Otherwise, the field can be created successfully. If you use it in sharepoint, an error will be reported!
Technorati tags: sharepoint, Field