I have a dynamic table with some textboxes (also dynamic) and some buttons which do postback onclick.
How can I make the page remember what text was entered in the boxes after postback, after clicking a button?
You have to create controls in a tymer click event.For that Create a new user control. Add public Properties in it for adding how much controls u have to add. And in Web user control Page INit and Page_load event Add the required number of controls. Hope this will work.
//IN web user control aspx page add a place holder in which u add your dynamic controls
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:PlaceHolder runat="server" ID="mycontrol"/>
// WEb User Control Code Behind
// Create public properties
public int totalnoOfcontrols
{
get;
set;
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// save values here
}
}
protected void Page_Init(object sender, EventArgs e)
{
// create dynamic controls here
TextBox t = new TextBox();
t.Text = "";
t.ID = "myTxt";
mycontrol.Controls.Add(t);
}
You have to use Page_Init/Load event handler to create controls runtime (dynamically).
For that you can use the ViewState
string data = ViewState["myData"];
ViewState["myData"] = data;
Related
I need to add a UserControl dynamicaaly to a Panel on a page. The UserControl has a Repeater with the ID of ARepeater. I load and add the UC on Page_Init. I examine the value of ARepeater in Init, Load, and PreRender events of UC but ARepeater is always null.
protected Page_Init(object sender, EventArgs e)
{
var list = (NameList)Page.LoadControl(typeof(NameList), new object[1] { (int)Type });
Panel1.Controls.Add(list);
}
The NameList.ascx
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="NameList.ascx.cs" Inherits="MyCompant.Controls.BannersList" %>
<asp:Repeater ID="ARepeater" runat="server">
<ItemTemplate>
</ItemTemplate>
</asp:Repeater>
What I am doing wrong?
First of all, you do not need to be in Page_Init to work with dynamic controls. Page_Load is just fine. But in order to fill the Repeater you can create a property in the UserControl
public partial class WebUserControl1 : System.Web.UI.UserControl
{
public Repeater _ARepeater
{
get
{
return ARepeater;
}
set
{
ARepeater = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
Then you can access it from the page using the UserControl.
protected void Page_Load(object sender, EventArgs e)
{
var list = (WebUserControl1)LoadControl("~/WebUserControl1.ascx");
list.ID = "MyUserControl";
Panel1.Controls.Add(list);
list._ARepeater.DataSource = source;
list._ARepeater.DataBind();
}
Or use FindControl
var _ARepeater = (Repeater)Panel1.FindControl("MyUserControl").FindControl("ARepeater");
_ARepeater.DataSource = dt;
_ARepeater.DataBind();
You probably won't like this answer, but the overload for Page.LoadControl that allows for specifying the control's type and adding constructor arguments doesn't bind the ascx to the code-behind, and all associated child-controls will end up being null.
In the past, I've worked around this by adding another method for setting dependencies after constructing the user control, but it's not an ideal solution.
That said you aren't doing anything wrong. Binding will work properly if you use Page.LoadControl("~/path/to/mycontrol.ascx"), but you won't have constructor injection.
I believe the issue lies with the fact that the backing class doesn't actually have a relationship with the front-end page, except through the page directive that specifies it as the code-behind class. Nothing stops multiple different front-ends using the same class as it's code-behind, so loading by Type makes it either very difficult or outright impossible to determine what the correct ascx to bind would be.
I have a dynamic data that has to be populated on UI from .cs file.
Currently I am doing it this way:
File.aspx
<div id="divLinks" class="w3-content w3-display-container" style="max-width:100%;" runat="server">
</div>
File.aspx.cs
StringBuilder str = new StringBuilder();
str.Append("<a target=\"_blank\"><img class=\"mySlides\" src=\"" + imageLink + "\" style=\"width:100%; height:350px;\" runat=\"server\" onServerClick=\"MyFuncion_Click("+link+")\" ></a>");
divLinks.InnerHtml = str.ToString();
protected void LinkButton_Click(object sender, EventArgs e)
{
//Do something when clicked a link with parameter from that link as identifier
}
After doing this, I am not able to reach LinkButton_Click function from onServerClick.
Can someone help me with this siince I want a link with unique value to be passed to function for further processing.
You are trying to add aspnet Controls to the page as a string. That is not gonna Work. You need to add "real" Controls to the page.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
//do not add dynamic controls here
}
//create a new ImageButton instance on every page load
ImageButton ib = new ImageButton();
//set some properties
ib.CssClass = "mySlides";
ib.ImageUrl = "~/myImage.png";
//add the click method
ib.Click += LinkButton_Click;
//add the button to an existing control
PlaceHolder1.Controls.Add(ib);
}
Note that you need to add dynamic controls on every Page Load, and that includes a PostBack.
Do web controls ever appear like you are changing their values but actually retain the previous value?
I created a pop-up modal for users to edit an item. When the user clicks edit on an item on the main page, the following sequence happens:
The item's ID is passed to the Page_Load event of the modal page, and is used to populate the page control's with the item's data.
The user changes a value in a control. Ex: Changes text in a TextBox contol.
The user clicks save, triggering the Click event which creates a DataTransferObject with the values in the textboxes, which will be stored.
However, on step 3, the control's new value (TextBox.Text) still holds the value that it orginially had, not the value the user put in.
Add.aspx:
<%# MasterType VirtualPath="../MasterPages/Popup.Master" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:TextBox ID="TextBoxDescription" runat="server"></asp:TextBox>
<telerik:RadButton ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"/>
</asp:Content>
Add.aspx.cs
//Cannot access the new values here
protected void btnSave_Click(object sender, EventArgs e)
{
//This will print the new text on Create, but the old text on Edit
System.Diagnostics.Debug.WriteLine(TextBoxDescription.Text);
}
//works properly
protected void Page_Load(object sender, EventArgs e)
{
objIDParam = Convert.ToInt64(Request.QueryString["ObjectID"]);
editMode = (objIDParam != 0) ? true : false;
if(editMode)
PopulateFields(objID);
}
//works properly
private void PopulateFields(long objID)
{
MyObject obj = GetObjectByID(objID);
TextBoxDescription.Text = obj.Description;
}
It is worth noting that this popup page is used for both creating items AND editing items. Create works fine (i.e. The item isn't saved with all blanks, but rather the user input). Editing an item will properly pull all that data back in, and let the user edit the fields, however I can't access the changed values in my code.
You need to check for IsPostBack in the Page_Load method.
The Page_Load gets called before the btnSave_Click method, so the TextBoxDescription.Text is getting reset to obj.Description before the btn_Save method runs.
Try returning out of Page_Load if you're posting back:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
return;
objIDParam = Convert.ToInt64(Request.QueryString["ObjectID"]);
editMode = (objIDParam != 0) ? true : false;
if(editMode)
PopulateFields(objID);
}
Have a look at ASP.NET Page Life Cycle Overview for more info.
This question already has an answer here:
ASP.NET Custom user control to add dynamically
(1 answer)
Closed 5 years ago.
I have a user control(UserControl1) on my page and one Add more button.Clicking on Add More Button add the same user control again.When i click on user control first time,it adds second User Control,but on second time it doesnot add other.I think the control gets lost.
I am adding a control like this on link button click:-
protected void lnkadd_Click(object sender, EventArgs e)
{
HtmlTableCell tCell = new HtmlTableCell();
UserControl uc = (UserControl)Page.LoadControl("~/Controls/DirectionalPricingCtrl.ascx");
tCell.Controls.Add(uc);
tablerow.Cells.Add(tCell);
}
I think i am doing something wrong and i should add user controls in respect of page life cycle,but how?
Can somebody please guide me or provide some useful links?
What approach i should follow when i have to add a user control each time when i click on a Add button and then later retrieve all the values and save it to DB?
I prefer javascript / ajax solution but I think there is nothing wrong with your code.
I did small example. Here is same solution as you have. Advantage is that control is loaded only in case of click.
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLink_Click(object sender, EventArgs e)
{
var uc = (UserControl)Page.LoadControl("~/WebUserControl1.ascx");
pnl.Controls.Add(uc);
}
}
Here is example where user control is loaded in Page_Load event and in case of click (btnLink_Click) user control is added to panel. It works same as your solution but user control can be loaded (processed in memory not redered) even if is not needed.
public partial class Default : System.Web.UI.Page
{
UserControl uc;
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack) // This condition is not needed but we know that click is always postback
uc = (UserControl)Page.LoadControl("~/WebUserControl1.ascx");
}
protected void btnLink_Click(object sender, EventArgs e)
{
pnl.Controls.Add(uc);
}
}
Here is solution which I prefer, it's based on visible property. In case that user control is not visible it's not rendered to output. Sure it's not very practival in case of table with lot of cells as a control container instead of panel.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<%# Register Src="~/WebUserControl1.ascx" TagName="ucrCtrl" TagPrefix="ctr" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnLink" runat="server" Text="Add" OnClick="btnLink_Click" />
<asp:Panel runat="server" ID="pnl">
<ctr:ucrCtrl runat="server" ID="usrCtrl" Visible="false" />
</asp:Panel>
</div>
</form>
</body>
</html>
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnLink_Click(object sender, EventArgs e)
{
usrCtrl.Visible = true;
}
}
}
Your code to add controls programmatically is right. Try doing,
tablerow.Cells.Add(tCell);
instead of adding it to the controls. this looks like a control rendering issue.
You thought right, your controls get lost due to a missing procedure which should handles post backs. Whenever you define a variable of a control-class such as HtmlTableCell, you should handle all procedures required for saving and loading data from posted page by yourself, instead of using predefined ones offered by asp.net run-time engine.
It's better to save and load those controls in some storage places during Postback such as ViewState on each post-back on PageLoad, then, handle adding/removing extra controls in lnkadd_Click method.
I have set of link buttons in my masterpage and one button in my content page.
i want when i click the any one of link button in the masterpage the value in the content page will change. How i can do this. Can any one able to help me because i am new in asp.net
Thank you
you can do something like this from your master page
var linkButton = ContentPlaceHolder1.FindControl("contentPageButton1") as LinkButton;
linkButton.Text = "Foo";
You can set it up with events.
In your master page:
public event EventHandler<EventArgs> SomethingChanged;
In your content page:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
((MyMasterPage)Page.Master).SomethingChanged += (s, ev) => UpdateStuff();
}