NeedHelp
NeedHelp

Reputation: 61

Adding groups of controls in C# userforms

I want to add X number of control groups, i.e. textbox field controls, to a form. I do not know how many there will be ahead of time, but I want to use the same validation logic for each type and to refer to them as such. For example,

Name (must be alphabet)
Age (must be numeric)

Does anyone know of the easiest way to do this? I'm not committed to using a textbox field either if something more suitable seems appropriate in this case.

Upvotes: 0

Views: 84

Answers (2)

bryanbcook
bryanbcook

Reputation: 18013

Assuming you mean WinForms, the Form object provides a collection of children controls. Simply instantiate the control and add it to the collection.

You could also assign an identifier to each control to indicate the validation logic to be used, for example:

var form = new MainWindow();
var input1 = new TextBox();
input.Height = 20;
input.Width = 30;
input.Top = 10;
input.Left = 10;
input.Tag = "email";
form.Controls.Add(input1);

When you perform validation later, iterate through the controls and then use the appropriate validator.

foreach(UserControl control in form.Controls)
{
   if (control.Tag == "email")
   {
      // validation against email control
   }
}

Upvotes: 0

Related Questions