Search code examples
c#asp.netdynamiccontrolsrequiredfieldvalidator

Add Required Validator on Dynamic Asp:net Table


I want to add some Required Validator on Controls(Textbox as example) in a dynamic asp:table.

Code:

   foreach (KeyValuePair<string, string> o in Collection)
    {
        TableRow Row = new TableRow();

        TableCell valueCell = new TableCell();
        TableCell Cell = new TableCell();
        TextBox txtBox = new TextBox();
        TextBox txtBox1 = new TextBox();


        txtBox1.ID = o.Key + o.Value;
                if (o.Value.Contains("Mandatory"))
                {
                    RequiredFieldValidator req = new RequiredFieldValidator();

                    req.ErrorMessage = "Required";
                    req.BorderColor = System.Drawing.Color.Red;
                    req.ControlToValidate = txtBox1.ID;
                    req.Enabled = true;
                    req.Display = ValidatorDisplay.Dynamic;

                    Cell.Controls.Add(req);
                }

        valueCell.Controls.Add(txtBox1);
        Row.Cells.Add(valueCell);
        Row.Cells.Add(Cell);
        table.Rows.Add(Row);
}

But i am getting this error:

" System.Web.UnhandledException in System.web.dll"

on the line Row.Cells.Add(Cell);

Can you help me ?


Solution

  • I fix the problem with a Panel which contains the Texbox and the RequireValidatorField.

        Panel p = new Panel();
        p.Controls.Add(txtBox1);
        p.Controls.Add(req);
        valueCell.Controls.Add(p);