开发者

Validate Sharepoint 2007 Web Part form field in C#

I am creating a very simple web part that accepts entry on a form text field and then does something with it. Before doing this, I want to validate the content of the text field. It must exist, and it must be less than 250 characters. I know I could probably write some custom code to do this, but Sharepoint includes Validation features, so why reinvent the wheel.

However, after an hour searching for some documentation on what I want to achieve, I have found plenty that explains how to do this if I am writing 开发者_StackOverflow中文版ASP.NET code, but very little if writing the web part in C# in Visual Studio 2008. The only bit remaining is the validation.

So, my question is how to validate a field on a form.

My field is called txtMessage. Here is the code I wrote:

// Add the form field to the web part
tc = new TableCell();
tc.VerticalAlign = VerticalAlign.Top;
txtMessage = new TextBox();
txtMessage.ID = "txtFormField";
txtMessage.Width = Unit.Pixel(300);
txtMessage.MaxLength = 250;
tc.Controls.Add(txtMessage);**strong text**

// Validate form field - required field
RequiredFieldValidator messageRequiredValidator = new RequiredFieldValidator();
messageRequiredValidator.ControlToValidate = txtMessage.ID;
messageRequiredValidator.ErrorMessage = "You must enter text";
messageRequiredValidator.Display = ValidatorDisplay.Dynamic;
messageRequiredValidator.Text = "<img src=\"/_layouts/images/CNSCA16.gif\"/>";

 // Send Message button
 tc = new TableCell();
 btnSendMessage = new Button();
 btnSendMessage.Text = "Send";
 btnSendMessage.Click += new EventHandler(btnSendMessage_Click);
 tc.Controls.Add(btnSendMessage);
 tr.Controls.Add(tc);

All I really need to know is how to trigger validation of the field when clicking on the button. Do I need to add a new EventHandler that calls the validation, or something else?


Doh - now I realise that I have to add this as a separate control to the page.

tc.Controls.Add(messageRequiredValidator);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜