asp.net - adding button with runatserver in back code - c#

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);

Related

System.Web.UI.WebControls.Button click event not firing

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();
}

ASP.Net Button and the onclick event don't work

I make a dynamic table with buttons in they cells, but when i click some button show me this error in console:
Uncaught ReferenceError: bttn_Click is not defined
at HTMLUnknownElement.onclick (VM51 panel.aspx:1)
this is how i make the button in html and asp.net :
StringBuilder htmlStr = new StringBuilder();
htmlStr.Append("<asp:button onclick='bttn_Click' class='btn btn-warning btn-xs' ID='Bttn_PDF'>PDF</asp:button>");
PlaceHolder1.Controls.Add(new Literal { Text = htmlStr.ToString() });
and the C#
protected void bttn_Click(object sender, CommandEventArgs e)
{
Button btn = (Button)sender;
string btnid = btn.CommandArgument;
test.Text = btnid;
}
This is because the onclick event actually expects a Javascript-specific event to be called and you are currently trying to call a server-side event instead. When defining such an event on an actual ASP.NET Button control, you instead want to use the OnClientClick event instead. But this doesn't really matter as you want to target a server-side event and not a client-side one.
Build Your Button Server-side
What you'll likely want to do is create an actual Button control, define a click event handler that points to your method, and then add that control to the page as opposed to building a string:
// Build your button with its specific properties
Button button = new Button();
button.ID = "Bttn_PDF";
button.CssClass = "btn btn-warning btn-xs";
// Wire up its click event
button.Click += bttn_Click;
// Add it to the form
PlaceHolder1.Controls.Add(button);

how can i use button click event and onclientclick together

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','');";

Command event not firing asp.net for dynamically created control

I've got the following code that creates an image button dynamically on a li html tag. When I click the image button it does not fire the event. What am I doing wrong please?
Code that generates the control:
ImageButton cmdEdit = new ImageButton();
cmdEdit.ImageUrl = "~/Images/phone_book_edit.png";
cmdEdit.ID = "cmdEdit" + recordcount.ToString();
cmdEdit.Attributes["class"] = "liQuestionsLabel2";
cmdEdit.Width = 30;
cmdEdit.CommandName = "Edit";
cmdEdit.CommandArgument = (recordcount - 1).ToString();
cmdEdit.Command += new CommandEventHandler(EditQuestion_Command);
li.Controls.Add(cmdEdit);
Event code:
protected void EditQuestion_Command(object sender, CommandEventArgs e)
{
Response.Write("here");
}
Dynamically generated controls lose their state after they are rendered. For you to access them again once you postback, you will have to recreate them in the code-behind along with recreating the attached events as well.
Put the above code in your Page_Load but not inside the if(!IsPostback) so that it gets recreated and you can then access its event.
Other than that, the above code works fine for me when I recreated the same control in my page.

Postback from Dynamic Content

I am dynamically building some HTML content on a WebForms page, using HtmlGenericControl().
HtmlGenericControl p = new HtmlGenericControl("p");
// ...
ListItems.Controls.Add(p);
But now I need to add a button to the paragraph created above, and the button needs to do a postback when clicked.
Must I completely rework this code to load child controls, which can contain real server-side buttons? Or is there a way to inject buttons capable of some type of postback?
Here's a test method and test EventHandler that, if called, will add a button control with a server-side Click event to ListItems. The commented-out code will change the markup of the ListItems object if InnerHtml is available but I rethought that approach and assumed the existence of a textbox on the page that would show the results of the click event firing. There are a number of concerns that you'll want to handle if you need those child controls to be present from one postback to another, though- for instance, if Test() isn't called every time the page loads that button won't be created and there will be no way to call its EventHandler unless other controls also call it.
public void Test()
{
System.Web.UI.HtmlControls.HtmlGenericControl p = new System.Web.UI.HtmlControls.HtmlGenericControl("p");
p.InnerHtml = #"<strong>Test</strong>";
// ...
ListItems.Controls.Add(p);
Button b = new Button();
b.ID = "cmdTest";
b.Text = "Test";
b.Click += new EventHandler(test_Click);
p.Controls.Add(b);
}
protected void test_Click(object sender, EventArgs e)
{
// ListItems.InnerHtml = "Test button clicked";
txtTestResults.Text = "Test button clicked at " + DateTime.Now.ToShortTimeString();
}

Categories