7

How to allow my control contains a text inside it's tags?

<uc:My runat="server">Text</uc:My>

My control contains a complex table and I want to put Text into one of cells. How to do that?

abatishchev
  • 92,232
  • 78
  • 284
  • 421

4 Answers4

7
[PersistChildren(false)]
[ParseChildren(true, "Text")]
public partial class RequiredFieldMarker : UserControl, ITextControl
{
    [Category("Settings")]
    [PersistenceMode(PersistenceMode.EncodedInnerDefaultProperty)]
    public string Text
    {
        get
        {
            return lblName.Text;
        }
        set
        {
            lblName.Text = value;
        }
    }
}
Chris Mullins
  • 6,207
  • 2
  • 27
  • 38
abatishchev
  • 92,232
  • 78
  • 284
  • 421
2

Have a property on your user control called Text, and set that like

<uc:My id="my" Text="some text" runat="server">Text</uc:My>

or server side

my.Text = "some text"; 
abatishchev
  • 92,232
  • 78
  • 284
  • 421
µBio
  • 10,371
  • 6
  • 36
  • 55
1

Assuming the UC generates a table, the easiest method I can think of is this:

In the UserControl's ascx do something like this:

<table>
  <tr>
     ....
     <td><asp:Literal runat="server" ID="ltCellContent" /></td>
     .... 
  </tr>
</table>

In the UserControl's code behind:

public string CellContent 
{ 
  get { return ltCellContent.Text; } 
  set { ltCellContent.Text = value; } }
}

And to use it:

<uc:My runat="server" CellContent="Some content" />
pbz
  • 8,185
  • 13
  • 52
  • 68
  • Yea, this is the most easy way. But I want to understand how to implement the task properly. Like asp:Label does. – abatishchev Dec 01 '09 at 22:39
  • 2
    @abatishchev: In that case you need to look into how custom controls are built; I recommend "Developing Microsoft ASP.NET Server Controls and Components" by Nikhil/Datye, V. Kothari. – pbz Dec 09 '09 at 19:08
  • When I try this, I get 'ltCellContent does not exist in the current context'. – Will Lanni Dec 11 '17 at 19:43
1

Just add one line before the class ([ParseChildren(true, "TestInnerText")]), and add a property named "TestInnerText". Create any control of your choice, I have created LiteralControl just to display inner html view.

"TestInnerText" - is just a temporary name I gave, you can use any property name of your choice.

Do the following change in my.aspx.cs file,

[ParseChildren(true, "TestInnerText")]
public partial class My : UserControl
{
    public string TestInnerText
    {
        set
        {
            LiteralControl lc = new LiteralControl();
            lc.Text = value;
            this.Controls.Add(lc);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
    }
}
George Livingston
  • 2,120
  • 12
  • 11