In my C# code I have function to dynamically create buttons
private Button createPageButton(string id, string text, int navTo = 0)
{
Button btn = new Button();
btn.ID = id;
btn.Text = text;
btn.Click += new EventHandler(btnNavigate_To_Page);
return btn;
}
Which gets setup like this:
C#:
public void someMethod()
{
Button btnPage_First = createPageButton("btnFirst_Page", "First", 1);
panelNavPageButtons.Controls.Add(btnPage_First);
}
aspx:
<asp:Panel ID="panelPageNavButtons" CssClass="pageNavBtns" runat="server"></asp:Panel>
Problem: The btnNavigate_To_Page event does not fire. The createPageButton method is not called within Page_Load but if I include an asp button in the panel (see below) then any additional button I add on the server side works properly
<asp:Panel ID="panelPageNavButtons" CssClass="pageNavBtns" runat="server">
<asp:Button ID="btnPage_Prev" runat="server" OnClick="btnNavigate_To_Page" />
</asp:Panel>
I would like to set up all the buttons dynamically without including any reference to btnNavigate_To_Page in the .aspx file
You have to call someMethod method inside either Init or Load event.
The reason is dynamically created controls are not in the control tree, so you have to reload them on every post back with same id.
protected void Page_Init(object sender, EventArgs e)
{
someMethod();
}
Related
How can I make this button
resultsHtml.Append(" <button runat="server" ID='btnHelloWorld' OnClick='btnHelloWorld_Click' Text='Upd`ate label!' /> ");
run this
protected void btnHelloWorld_Click(object sender, EventArgs e)
{
lblHelloWorld.Text = "Hello, world";
}
In the same page?
They are both in the back code and the same page. The reason I put it in resultsHtml.Append(); is because it's in the datatable
Dont take whole button HTML script from database. Just take button name and onClick event name from database.
Then create button dynamically from code behind as follow:
Button btnHelloWorld= new Button();
btnHelloWorld.ID = "btnEdit";
btnHelloWorld.Text = "Edit";
btnHelloWorld.Click += new EventHandler(btnHelloWorld_Click);
form1.Controls.Add(btnHelloWorld);
I have a webpage Containing UserControl repeated 2 times with same functionality. I want to disable the textbox in first UserControl but it is getting disabled in 2nd UserControl.
How to check this?
<script type="text/javascript">
function confirmCallBackFn(arg)
{
if (arg == true)
{
$find('<%= txtOne.ClientID %>').disable();
}
}
Method 1 - If the event is triggered by a control in the parent form
In the user control, you can define a property that returns the ID of the TextBox:
public string TextBoxID
{
get { return txtOne.ClientID; }
}
If your form contains two instances of the user control, ctrl1 and ctrl2, you can target a specific one like this:
document.getElementById('<%= ctrl1.TextBoxID %>').disabled = true;
Note: In the user control, make sure that you don't use ClientIDMode="Static" for the inner controls.
Method 2 - If the event is triggered by an inner control of the user control
If your user control contains the following markup:
<asp:CheckBox ID="chk1" runat="server" />
<asp:TextBox ID="txtOne" runat="server" />
you can add Javascript event handlers to the CheckBox in the Page_Load method of the user control:
protected void Page_Load(object sender, EventArgs e)
{
string js = string.Format("txtBoxID = '{0}';", txtOne.ClientID);
chk1.Attributes.Add("onmousedown", js);
chk1.Attributes.Add("onkeydown", js);
}
These event handlers set the value for a txtBoxID variable that you can define and use in your Javascript block:
<script type="text/javascript">
var txtBoxID;
function confirmCallBackFn(arg) {
if (arg == true) {
document.getElementById(txtBoxID).disabled = true;
}
}
</script>
This method assumes that there is no postback during the process. If a postback occurs, we may have to modify that method and register a script in the event handler in code-behind.
I want to create a dynamic button when click a pop up appear and user key in then submit.
First of all I have dynamic button created depends on the table row
TableCell tc;
for (int i = 1; i < Approval_TBL.Rows.Count; i++)
{
TableRow tr = Approval_TBL.Rows[i];
tr.Cells.Add(tc = new TableCell());
Button tb = new Button();
tb.ID = Convert.ToString(i);
tb.Text = "Reject";
tb.CssClass = "btn btn-default";
tb.OnClientClick = "javascript:$find('popup1').show();return false;__doPostBack('btnReject_click','')";
tb.Click += new EventHandler(btnReject_click);
tc.Controls.Add(tb);
}
then I have the popup created using ajax:
<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
TargetControlID="1"
BehaviorID="popup1"
PopupControlID="Panel1"
DropShadow="true"
CancelControlID="Button3"
OnOkScript="OkButtonClick"
BackgroundCssClass="BackgroundStyle" />
then I have created click event
protected void btnReject_click(object sender, EventArgs e)
{
//code
}
Currently looks like it only run Onclientclick event where the popup appear but it wont go in to btnReject_click. but if i remove the onclientclick, it will be able to go in the btnReject_click.
My way of doing is weird because i dont know how to use asp.net and most of my code i put it in server side (c#).
if you using jQuery then
$("selector").on('click',function(){
// your code here
});
Within your OnClientClick you return false;. Anything after that is not executed so the postback never happens. Remove the return and the postback should fire.
tb.OnClientClick = $find('popup1').show();__doPostBack('btnReject_click','');";
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;
<asp:Button onclick="Some_event" Text="Add TextBox" ID="id1" runat="server" />
//once clicked:
<asp:TextBox ID="txt1" ......></asp:TextBox>
//when clicked again:
<asp:TextBox ID="txt1" ......></asp:TextBox>
<asp:TextBox ID="txt2" ......></asp:TextBox>
//and so on...
Is there a way to create dynamic controls which will persist even after the postback? In other words, when the user clicks on the button, a new textbox will be generated and when clicks again the first one will remain while a second one will be generated. How can I do this using asp.net ? I know that if I can create the controls in the page_init event then they will persist but I dont know if it possible to handle a button click before the page_init occurs, therefore there must be another way.
Yes, this is possible. One way to do this using purely ASP.NET (which seems like what you're asking for) would be to keep a count of the TextBox controls that you have added (storing that value in the ViewState) and recreate the TextBox controls in the Page_Load event. Of course, nowadays most people would probably use Javascript or jQuery to handle this task client side, but I put together a quick example to demonstrate how it works with postbacks:
Front page:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="DynamicControls.aspx.cs" Inherits="MyAspnetApp.DynamicControls" EnableViewState="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"></head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnAddTextBox" runat="server" Text="Add" OnClick="btnAddTextBox_Click" />
<asp:Button ID="btnWriteValues" runat="server" Text="Write" OnClick="btnWriteValues_Click" />
<asp:PlaceHolder ID="phControls" runat="server" />
</div>
</form>
</body>
</html>
Code behind:
using System;
using System.Web.UI.WebControls;
namespace MyAspnetApp
{
public partial class DynamicControls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Recreate textbox controls
if(Page.IsPostBack)
{
for (var i = 0; i < TextBoxCount; i++)
AddTextBox(i);
}
}
private int TextBoxCount
{
get
{
var count = ViewState["txtBoxCount"];
return (count == null) ? 0 : (int) count;
}
set { ViewState["txtBoxCount"] = value; }
}
private void AddTextBox(int index)
{
var txt = new TextBox {ID = string.Concat("txtDynamic", index)};
txt.Style.Add("display", "block");
phControls.Controls.Add(txt);
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
AddTextBox(TextBoxCount);
TextBoxCount++;
}
protected void btnWriteValues_Click(object sender, EventArgs e)
{
foreach(var control in phControls.Controls)
{
var textBox = control as TextBox;
if (textBox == null) continue;
Response.Write(string.Concat(textBox.Text, "<br />"));
}
}
}
}
Since you are recreating the controls on each postback, the values entered into the textboxes will be persisted across each postback. I added btnWriteValues_Click to quickly demonstrate how to read the values out of the textboxes.
EDIT
I updated the example to add a Panel containing a TextBox and a Remove Button. The trick here is that the Remove button does not delete the container Panel, it merely makes it not Visible. This is done so that all of the control IDs remain the same, so the data entered stays with each TextBox. If we were to remove the TextBox entirely, the data after the TextBox that was removed would shift down one TextBox on the next postback (just to explain this a little more clearly, if we have txt1, txt2 and txt3, and we remove txt2, on the next postback we'll create two textboxes, txt1 and txt2, and the value that was in txt3 would be lost).
public partial class DynamicControls : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
for (var i = 0; i < TextBoxCount; i++)
AddTextBox(i);
}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
AddTextBox(TextBoxCount);
TextBoxCount++;
}
protected void btnWriteValues_Click(object sender, EventArgs e)
{
foreach(var control in phControls.Controls)
{
var panel = control as Panel;
if (panel == null || !panel.Visible) continue;
foreach (var control2 in panel.Controls)
{
var textBox = control2 as TextBox;
if (textBox == null) continue;
Response.Write(string.Concat(textBox.Text, "<br />"));
}
}
}
private int TextBoxCount
{
get
{
var count = ViewState["txtBoxCount"];
return (count == null) ? 0 : (int) count;
}
set { ViewState["txtBoxCount"] = value; }
}
private void AddTextBox(int index)
{
var panel = new Panel();
panel.Controls.Add(new TextBox {ID = string.Concat("txtDynamic", index)});
var btn = new Button { Text="Remove" };
btn.Click += btnRemove_Click;
panel.Controls.Add(btn);
phControls.Controls.Add(panel);
}
private void btnRemove_Click(object sender, EventArgs e)
{
var btnRemove = sender as Button;
if (btnRemove == null) return;
btnRemove.Parent.Visible = false;
}
}
I read an article by Scott Mitchell that explains that ViewState only persists changed control state across post-back, and not the actual controls themselves. I did not have your exact scenario, but a project I was working on required dynamically added user controls and I had to add them on every postback. In that case, it is still useful to create them in Init so that they can retain their state. Here is the link: Understanding ASP.NET View State. Check section “View State and Dynamically Added Controls”.
You may have to keep track of all the controls that you are adding (in session state for example) and re-create them on post back. I just did a small test where I keep a List<string> of all the Textbox ids in Session. On postback, I recreate all the textboxes.