I put some self made Web User Controls in a seperate Project "WebControls" and now want to reuse them from another Project
My Control consists of:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="TestControl.ascx.cs" Inherits="WebControls.TestControl" %>
<asp:Label ID="lblTest" runat="server" ></asp:Label>
<asp:TextBox ID="textBox" runat="server" Width="" />
<asp:HiddenField ID="hiddenFieldId" runat="server" />
with Code Behind:
namespace WebControls
{
public partial class TestControl : System.Web.UI.UserControl
{
public Unit Width
{
get { return textBox.Width; }
set { textBox.Width = value; }
}
public string SelectedId
{
get { return hiddenFieldId.Value; }
set { hiddenFieldId.Value = value; }
}
public string SelectedText
{
get { return textBox.Text; }
set { textBox.Text = value;}
}
protected void Page_Init(object sender, EventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
I bind it into a Webpage in the other project like that:
<%@ Page Title="ToDo Serien" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="True" CodeBehind="RecurringToDos.aspx.cs" Inherits="TestAccess.RecurringToDos" %>
<%@ Register Assembly="WebControls" Namespace="WebControls" TagPrefix="aci" %>
<asp:Content runat="server" ID="FeaturedContent" ContentPlaceHolderID="FeaturedContent">
<section class="featured">
<div class="content-wrapper">
<hgroup class="title">
<h1><%: Title %>.</h1>
<h2>Serienelement</h2>
<aci:TestControl ID="aceRule" runat="server" Width="300" />
<asp:Button ID="btnSend" runat="server" OnClick="btnSend_Click" />
</hgroup>
</div>
....
When I now start the page it throws a Reference Null Exception in following line:
set { textBox.Width = value; }
becuase textBox = NULL
Seems my Control is not properly initiated. What am I doing wrong? How can I fix that?
If you want to reuse a
ascxuser control across multiple projects, you should copyascxfile to the consumer project and register the tag this way:As an example, you can follow these steps:
Create a new web project name it
WebUserControlsAdd a Web Forms User Control and name it
UserControl1and in code behind add:
In the consumer project, add a reference to the project containing the
ascxuser control.Copy
.ascxfile of control into the consumer project.Note: You don't need to add the file to the project, but the physical file should exist in the path which you used as
Srcin registerting the tag.In the page which you want to use the control, add this:
Use the control this way:
Note
If you want to not copy ascx file, you can use Web Forms Server Control which doesn't rely on
ascxfiles. Then for using those custom controls, it's enough to register them: