How can I create a WebControl in ASP.NET that has public properties tied to the input elements of a form?

StackOverflow https://stackoverflow.com/questions/15375285

Question

In short, I want to create a WebControl that may appear multiple times in an input form. The WebControl I've drafted out has properties that are assumed to be related to the values in the web control (text boxes etc.) What I want to be able to do is access the contents of the WebControl's input elements by name in my submit handler as below:

var firstname = customControl.FirstName;
var lastname = customControl.LastName;

I come from a WPF background so this is just familiar enough I am getting myself into trouble.

Was it helpful?

Solution

This is off the top of my head (just getting back to .NET after a few months on other languages), and I'm assuming it's for a User control because Server controls are pretty well documented for properties.

First, assume your user control has textboxes txtFirst and txtLast.

In the code-behind, add public properties FirstName and LastName. The properties would look like this:

public string FirstName {
 get { return this.txtFirst.Text.Trim(); }
 set { this.txtFirst.Text = value ?? ""; }
}

public string LastName {
 get { return this.txtLast.Text.Trim(); }
 set { this.txtLast.Text = value ?? ""; }
}

That's it. My apologies if you weren't asking about a user control.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top