Set value to TextBox in UserControl inside placeholder - asp.net

I have an textbox inside an user control. I created dinamically this user control and load in placeholder.
But when I tried to assign a value to the textbox, I raised next below error:
Object reference not set to an instance of an object
This is the user control:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="IVT_FormClient.ascx.cs" Inherits="Evi.Sc.Web.Evi.IVT.Sublayouts.IVT_FormClient" %>
<asp:Panel ID="pnlContainer" runat="server">
<asp:TextBox ID="txtClientNumber" runat="server"></asp:TextBox>
</asp:Panel>
The access modifier is (In the user control):
public string TxtFirstName
{
get { return txtFirstName.Text; }
set { txtFirstName.Text = value; }
}
In the web form I have the control reference:
<%# Reference Control="~/Evi/IVT/Sublayouts/IVT_FormClient.ascx" %>
In the code behind of the user control is:
public partial class frm_VerifyIdentity : System.Web.UI.Page
{
IVT_FormClient ivtFormClient = new IVT_FormClient();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
IVT_FormClient ivtFormClient = (IVT_FormClient)LoadControl("~/Evi/IVT/Sublayouts/IVT_FormClient.ascx");
Client UserClient = new Client();
UserClient = Load_ClientVerification(Server.HtmlEncode(Request.QueryString["ID"]).Trim());
if (UserClient != null)
{
ivtFormClient.TxtFirstName = UserClient.FirstName;
plhFormClient.Controls.Add(ivtFormClient);
}
}
}
}
The error occur is this line of code:
ivtFormClient.TxtFirstName = UserClient.FirstName;

Do not create an instance of a UserControl via constructor but with LoadControl as you have already done in Page_Load. However, you are doing that only if(!IsPostBack). Hence the control is instantiated the next postback via constructor.
Also, you have to recreate dynamic controls on every postback. I would suggest to add the UserControl delaratively to the page. You can hide/show it accordingly. Otherwise you need to create/add it always, best in Page_Init instead of Page_Load.
So this is not best-practise(just add it to the page) but should work as desired:
IVT_FormClient ivtFormClient = null;
protected void Page_Init(object sender, EventArgs e)
{
ivtFormClient =(IVT_FormClient)LoadControl("~/Evi/IVT/Sublayouts/IVT_FormClient.ascx");
Client UserClient = new Client();
UserClient = Load_ClientVerification(Server.HtmlEncode(Request.QueryString["ID"]).Trim());
if (UserClient != null)
{
ivtFormClient.TxtFirstName = UserClient.FirstName;
plhFormClient.Controls.Add(ivtFormClient);
}
}

Related

how to access master page control from content page

I have a master page which contains a label for status messages. I need to set the status text from different .aspx pages. How can this be done from the content page?
public partial class Site : System.Web.UI.MasterPage
{
public string StatusNachricht
{
get
{
return lblStatus.Text;
}
set
{
lblStatus.Text = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
}
I have tried this, but was unsuccessful in making it work:
public partial class DatenAendern : System.Web.UI.Page
{
var master = Master as Site;
protected void Page_Load(object sender, EventArgs e)
{
if (master != null)
{
master.setStatusLabel("");
}
}
protected void grdBenutzer_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
//some code
if (master != null)
{
master.setStatusLabel("Passwort erfolgreich geändert.");
}
}
catch (Exception ex)
{
if (master != null)
{
master.setStatusLabel("Passwort konnte nicht geändert werden!");
}
}
}
}
}
In the MasterPage.cs file add the property of Label like this:
public string ErrorMessage
{
get
{
return lblMessage.Text;
}
set
{
lblMessage.Text = value;
}
}
On your aspx page, just below the Page Directive add this:
<%# Page Title="" Language="C#" MasterPageFile="Master Path Name"..... %>
<%# MasterType VirtualPath="Master Path Name" %> // Add this
And in your codebehind(aspx.cs) page you can then easily access the Label Property and set its text as required. Like this:
this.Master.ErrorMessage = "Your Error Message here";
In Content page you can access the label and set the text such as
Here 'lblStatus' is the your master page label ID
Label lblMasterStatus = (Label)Master.FindControl("lblStatus");
lblMasterStatus.Text = "Meaasage from content page";
It Works
To find master page controls on Child page
Label lbl_UserName = this.Master.FindControl("lbl_UserName") as Label;
lbl_UserName.Text = txtUsr.Text;
I have a helper method for this in my System.Web.UI.Page class
protected T FindControlFromMaster<T>(string name) where T : Control
{
MasterPage master = this.Master;
while (master != null)
{
T control = master.FindControl(name) as T;
if (control != null)
return control;
master = master.Master;
}
return null;
}
then you can access using below code.
Label lblStatus = FindControlFromMaster<Label>("lblStatus");
if(lblStatus!=null)
lblStatus.Text = "something";
You cannot use var in a field, only on local variables.
But even this won't work:
Site master = Master as Site;
Because you cannot use this in a field and Master as Site is the same as this.Master as Site. So just initialize the field from Page_Init when the page is fully initialized and you can use this:
Site master = null;
protected void Page_Init(object sender, EventArgs e)
{
master = this.Master as Site;
}
This is more complicated if you have a nested MasterPage. You need to first find the content control that contains the nested MasterPage, and then find the control on your nested MasterPage from that.
Crucial bit: Master.Master.
See here: http://forums.asp.net/t/1059255.aspx?Nested+master+pages+and+Master+FindControl
Example:
'Find the content control
Dim ct As ContentPlaceHolder = Me.Master.Master.FindControl("cphMain")
'now find controls inside that content
Dim lbtnSave As LinkButton = ct.FindControl("lbtnSave")
If you are trying to access an html element: this is an HTML Anchor...
My nav bar has items that are not list items (<li>) but rather html anchors (<a>)
See below: (This is the site master)
<nav class="mdl-navigation">
<a class="mdl-navigation__link" href="" runat="server" id="liHome">Home</a>
<a class="mdl-navigation__link" href="" runat="server" id="liDashboard">Dashboard</a>
</nav>
Now in your code behind for another page, for mine, it's the login page...
On PageLoad() define this:
HtmlAnchor lblMasterStatus = (HtmlAnchor)Master.FindControl("liHome");
lblMasterStatus.Visible =false;
HtmlAnchor lblMasterStatus1 = (HtmlAnchor)Master.FindControl("liDashboard");
lblMasterStatus1.Visible = false;
Now we have accessed the site masters controls, and have made them invisible on the login page.

value of private variable is not maintained after page load even in ASP.NET

I have two pages. first.aspx and second.aspx. In order to get all the control values from first.aspx, i added directive to second.aspx
<%# PreviousPageType VirtualPath="~/PR.aspx" %>
I have no problem to get all the previous page controls and set it to labels, but i have a big problem to save those values to a private variable, and reuse it after page load event is done. Here is code example. when i try to get the value from input in another method, it has nothing added. Why?
public partial class Second : System.Web.UI.Page
{
List<string> input = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (Page.PreviousPage != null&&PreviousPage.IsCrossPagePostBack == true)
{
TextBox SourceTextBox11 (TextBox)Page.PreviousPage.FindControl("TextBox11");
if (SourceTextBox11 != null)
{
Label1.Text = SourceTextBox11.Text;
input.Add(SourceTextBox11.Text);
}
}
}
protected void SubmitBT_Click(object sender, EventArgs e)
{
//do sth with input list<string>
//input has nothing in it here.
}
}
The SubmitBT_Click-click event happens in a postback. But all variables (and controls) are disposed at the end of the page's lifecycle. So you need a way to persist your List, e.g. in the ViewState or Session.
public List<String> Input
{
get
{
if (Session["Input"] == null)
{
Session["Input"] = new List<String>();
}
return (List<String>)Session["Input"];
}
set { Session["Input"] = value; }
}
Nine Options for Managing Persistent User State in Your ASP.NET Application

Can't get 'Text' property with asp-control

How do I get properties (e.g. Text) with asp.net controls that were created programatically when page loading when IsPostBack parameter is true?
Schema:
creating control (e.g. TextBox box = new TextBox(); box.ID = "BoxID")
display control in page (e.g. SomeControlInPageID.Controls.Add(box))
user see this textbox (with id "BoxID", but we don't have a possibility to get text property use BoxID.Text, because it control was created programatically!) in page & puts in it some text
user click in button (asp:Button) in page and start page reloading process
start Page_Load method & IsPostBack parameter takes the true value
i try to use this code to get Text property in Page_Load method, but it's not work...:
void Page_Load()
{
if (Page.IsPostBack)
{
TextBox box = SomeControlInPageID.FindControl("BoxID") as TextBox;
string result = box.Text;
}
else
{
// creating controls programatically and display them in page
...
}
}
box.Text in this code always takes null value.
The key here is you need to make sure you recreate the dynamic controls each time the page is loaded. Once the controls are created, ASP.NET will be able to fill the posted back values into those controls. I've included a full working example below. Notice I add the control in the OnInit event (which will fire before Page_Load), and then I can read the value back out in the Page_Load event if a postback has occurred.
<%# Page Language="C#" AutoEventWireup="true" %>
<html>
<body>
<form id="form1" runat="server">
<asp:Panel ID="myPanel" runat="server" />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" />
<br />
Text is: <asp:Literal ID="litText" runat="server" />
</form>
</body>
</html>
<script runat="server">
protected void Page_Load(object sender, System.EventArgs e)
{
if(Page.IsPostBack)
{
var myTextbox = myPanel.FindControl("myTextbox") as TextBox;
litText.Text = myTextbox == null ? "(null)" : myTextbox.Text;
}
}
protected override void OnInit(EventArgs e)
{
AddDynamicControl();
base.OnInit(e);
}
private void AddDynamicControl()
{
var myTextbox = new TextBox();
myTextbox.ID = "myTextbox";
myPanel.Controls.Add(myTextbox);
}
</script>
Please have a look into pageLifeCycle of an aspx page. You'll have to add the textbox within the Page_Init handler. Afterwards you may access your textBox in page_load event.
protected void Page_Init(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.ID = "textbox1";
tb.AutoPostBack = true;
form1.Controls.Add(tb);
}
protected void Page_Load(object sender, EventArgs e)
{
/// in case there are no other elements on your page
TextBox tb = (TextBox)form1.Controls[1];
/// or you iterate through all Controls and search for a textbox with the ID 'textbox1'
if (Page.IsPostBack)
{
Debug.WriteLine(tb.Text); /// only for test purpose (System.Diagnostics needed)
}
}
hth

Viewstate null on postback

So I have a listbox on my page and some textfields. Through the textfields I can add an item to my listbox (click the button, it adds it to a private List which is then set as a ViewState and the list is databound again). My listbox is also in an updatepanel which gets triggered on the button's Click event. Problem: My Viewstate remains null on a postback so it gets reset each time.
Some code:
private const string VIEW_INGREDIENTS = "IngredientsList";
private const string VIEW_LANGUAGE = "CurrentLanguage";
private List<IngredientData> _ingredientsList;
protected void Page_PreInit(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
if (ViewState[VIEW_INGREDIENTS] != null)
{
_ingredientsList = (List<IngredientData>) ViewState[VIEW_INGREDIENTS];
}
}
else
{
// prepare ingredient lists
_ingredientsList = new List<IngredientData>();
}
}
protected void Page_Load(object sender, EventArgs e)
{
lstIngredients.DataSource = _ingredientsList;
lstIngredients.DataTextField = "Text";
lstIngredients.DataValueField = "Name";
lstIngredients.DataBind();
}
protected void btnAddIngredient_Click(object sender, EventArgs e)
{
_ingredientsList.Add(new IngredientData { Name = txtIngredientName.Text, Quantity = txtUnitQuantity.Text, Unit = lstUnits.SelectedValue });
ViewState[VIEW_INGREDIENTS] = _ingredientsList;
lstIngredients.DataSource = _ingredientsList;
lstIngredients.DataBind();
}
You're using vewstate during PreInit ? Try to check that a bit later during PreLoad.
Check if the page has EnableViewState="true":
<%# Page Language="C#" EnableViewState="true" ...
And verify the site-wide setting in web.config:
<pages enableViewState="true" enableViewStateMac="true" ... />
Now ASP.NET has built-in viewstate for list controls, so I wonder why you're writing custom code for it. The default viewstate should work well for what you're trying to accomplish.

ASP.NET Custom user control to add dynamically

I have hard time to modify a page that had a Custom User Control directly to the ASPX page and now require to have it dynamically loaded when needed only. The User Control does have html and other controls via the ASCX file and has code in the code-behind.
I have read multiple page and have found that I cannot instantiate directly the User Control but should use the Page.LoadControl(...). The problem is not the compiling but when the page load the control it happen that all controls inside the ASCX are null and then crash.
How can I use a User Control that has code in the ASCX and in the code-behind dynamically?
Edit:
Example of what I am doing in (PageLoad or PagePreRender or PagePreInit)
Control c = LoadControl(typeof(MyControl), null);
myControl= (MyControl)c;
myControl.ID = "123";
myControl.Visible = false;
Controls.Add(myControl);
MyControl does have for example <div id="whatever" runat="server">... and inside the MyControl it set the visibility to True or False... but when it does that, now it crash because the "whatever" div is NULL.
What I have done is use the Page.LoadControl method in the Page_Init to add the custom user control to a place holder on the page.
protected void Page_Init(object sender, EventArgs e)
{
//MyControl is the Custom User Control with a code behind file
MyControl myControl = (MyControl)Page.LoadControl("~/MyControl.ascx");
//UserControlHolder is a place holder on the aspx page
// where I want to load the user control to
UserControlHolder.Controls.Add(myControl);
}
This works fine for me.
Here is the code for the dynamically loaded user control:
MyControl.ascx.cs
public partial class MyControl : System.Web.UI.UserControl
{
protected void Page_Init(object sender, EventArgs e)
{
LiteralControl lit = new LiteralControl("Test Literal Control");
Page.Controls.Add(lit);
}
protected void Page_Load(object sender, EventArgs e)
{
whatever.Visible = true;
if (IsPostBack)
{
whatever.Visible = false;
}
}
}

Resources