An .ascx
file, also known as a UserControl
is a good way reusing common html / code behind throughout a project. They're essentially just a container for other .NET controls.
So let's pretend you have a very simple form where you're just asking for a person's name and age, and for some reason you want this used many times in a page or on several pages...
UserControl1.ascx
markup:
<asp:Label runat="server" id="lblName" Text="What is the person's name?" AssociatedControlID="txtName"></asp:Label>
<asp:TextBox runat="server" id="txtName"></asp:TextBox>
<asp:Label runat="server" id="lblAge" Text="What is the person's age?" AssociatedControlID="txtAge"></asp:Label>
<asp:TextBox runat="server" id="txtAge"></asp:TextBox>
<asp:Button runat="server" id="btnSubmit" Text="Submit" Onclick="btnSubmit_Click"></asp:Button>
code behind:
private Person _Person;
protected void btnSubmit_Clicked(object sender, EventArgs args)
{
_Person = new Person() { Name = txtName.Text, Age = txtAge.Text };
}
public Person GetPerson()
{
return _Person;
}
Then on some other page you just drop this user control in, and you can reference it like this:
Default.aspx
markup:
<%@ Register src="UserControl1.ascx" tagname="UserControl1" tagprefix="uc1" %>
<html>
...blah blah...
<p>Tell us about you</p>
<uc1:UserControl1 ID="ucYou" runat="server" />
<p>Tell us about your friend</p>
<uc1:UserControl1 ID="ucYourFriend" runat="server" />
.. blah blah
</html>
code behind:
protected void SomeMethodThatSavesPage()
{
// other stuff
Person you = ucYou.GetPerson();
Person yourFriend = ucYourFriend.GetPerson();
}
Page Directive
As Robert reminded me in the comments, you need to make sure the page using the UserControl has the correct page directive at the top. If you are in design view and just drag the UserControl onto the page, Visual Studio will handle this for you. Otherwise, you need to include it yourself.