ASP.NET UserControl - null reference?

I have a problem with my user control. Inside I have a checkbox. I want to create this user control on the fly and paste it into asp: table control.

MyControl pp = new MyControl(); pp.pageNameCb.Text = "lorem"; TableCell tc = new TableCell(); tc.Controls.Add(pp); table.Rows[0].Cells.Add(tc); 

But pageNameCb is null, even if I create it manually, nothing is displayed in my table. Why?

Here is my code:

  <asp:View ID="new_role_view" runat="server"> <asp:Table ID="table1" runat="server"> <asp:TableRow ID="TableRow1" runat="server"> <asp:TableCell ID="TableCell1" runat="server"> </asp:TableCell> </asp:TableRow> </asp:Table> </asp:View> 

Then, if I change this view, I create my control:

  MyControl pp = new MyControl(); table.Rows[0].Cells[0].Controls.Add(pp); 

MyControl Page_Init:

  protected void Page_Init(object sender, EventArgs e) { if (pageNameCb == null) pageNameCb = new CheckBox(); pageNameCb.Text = "works"; } 

and yet shows nothing

+4
source share
2 answers

When you create a user control, do you create a checkbox at the same time? It will be zero if the flag is not created at some point. If it were a user control that you would create in Control.CreateChildControls - how could it be a user control in the constructor or a user method - Init () or somesuch.

In addition, I would create a user control on the page_Init, and then add it to the control tree, otherwise it will not participate in the ViewState page.

0
source

This is code that should work fine if your user control is well-designed in accordance with the ASP.net Page Cycle .

Initialize the flag in the User Control Page_Init () element if you add this flag dynamically. and provide you with an ID .

  private Table CreateHtmlTable() { Table table = new Table(); table.Rows.Add(new TableRow()); TableCell tc = new TableCell(); MyControl pp = new MyControl(); pp.ID = "SomeID"; pp.pageNameCb.Text = "lorem"; tc.Controls.Add(pp); table.Rows[0].Cells.Add(tc); return table; } 

This is code that works great for me ...

 ASPxLabel lbl = new ASPxLabel(); lbl.ID = "lblTopicName"; lbl.Text = "TopicName"; table.Rows[0].Cells[0].Controls.Add(lbl); 
0
source

Source: https://habr.com/ru/post/1384288/


All Articles