Friday, November 6, 2009

Disabling SharePoint TextField control programmatically from a Webpart.


I was involved in a MOSS project, where my client developed a webpart which is essentially a data entry form for a list using SharePoint Controls. The client ran into an issue, when he was trying to disable the Textfield control programmatically from the webpart for a certain set of users. The webpart used CreateChildControls() method to dynamically create the controls. This is a code snippet from CreateChildControls() within the webpart.

protected override void CreateChildControls()

{

TextField txtTitle = new TextField();

txtTitle.ListId = listGuid;

txtTitle.ItemId = itemId;

txtTitle.FieldName = "SampleTitle";

Controls.Add(txtTitle);

}

Currently there is no property available to change the Textfield control's state to disabled or read only mode. The following is a work-around to disable the control. This code registers a JavaScript function in the web part which in turn disables the controls and changes it to read only mode.

Step 1. Add the following JavaScript function to a common script file which is referred from the master page.

<script type="text/javascript">

/*This method returns the first object which

matches the tagname and part of the id passed as parameter*/

function getElementByPartOfID(idPart, tagName)

{

var tags = document.getElementsByTagName(tagName);

for (var i=0; i < tags.length; i++)

{

var tempString = tags[i].id;

if ( tempString.indexOf(idPart) >= 0 )

{

return document.getElementById(tempString);

}

}

return null;

}

</script>

Step 2. Add the following code to CreateChildControls() method in your webpart as follows. This code iterates though the controls collection and dynamically creates a JavaScript function which disables the controls.

// Create dynamic Javascript string to disable the text boxes

StringBuilder strDisableScript = new StringBuilder();

strDisableScript.Append("<script>\n");

strDisableScript.Append(" disableitems();\n");

strDisableScript.Append(" function disableitems()\n");

strDisableScript.Append(" {\n");

foreach (Control ctrl in Controls)

{

strDisableScript.Append("var ctl = getElementByPartOfID('" + ctrl.ClientID + "','input');\n");

strDisableScript.Append("if(ctl !=null) ctl.disabled = true;\n");

}

strDisableScript.Append(" } </script> ");

string uniqueScriptID = "disableScript_" + Guid.NewGuid();

if (!Page.ClientScript.IsClientScriptBlockRegistered(uniqueScriptID))

Page.ClientScript.RegisterStartupScript(typeof(Page), uniqueScriptID, strDisableScript.ToString());

0 comments: