Disable postback of a dynamically created button asp.net - asp.net

This is my Page1.aspx code:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:Panel ID="Panel1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
</asp:Panel>
</asp:Content>
This is my Page1.aspx.cs code
public partial class Page1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == true)
{
btn_Click(sender, e);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn.Text = "Dynamic button";
btn.Click += btn_Click;
Panel1.Controls.Add(btn);
}
void btn_Click(object sender, EventArgs e)
{
Response.Redirect("../Page2");
}
}
From this code, when "Button1" is clicked it should create a new button "btn" and when "btn" is clicked, it should go to the url in its click function (i.e. btn_Click()). But when I click "Button1" it does not execute "Button1_Click()" but "btn_Click()". What should I do??

if (IsPostBack == true)
can become
if (IsPostBack)
Then
Response.Redirect("../Page2");
can become
Response.Redirect("~/Page2");
In the aspx check you have:
<asp:Button runat="server" ID="Button1" OnClick="Button1_Click"></asp:Button>
Moreover you can bind click in code behind (eg OnLoad):
Button1.Click += Button1_Click;
and also unbind:
Button1.Click -= Button1_Click;

Related

asp.net button in ITemplate doesn't fire Repeater ItemCommand event

i am a complete asp.net noob and the solution could be something very simple.
i have found, read and tried many answers to questions very similar to my question, but nothing works. i hope to find some help here.
this works perfectly with no problem:
<asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text='<%# (Container.DataItem as Choice).description %>' CommandName="Choice" CommandArgument='<%# (Container.DataItem as Choice).id %>'/>
<br />
</ItemTemplate>
</asp:Repeater>
code behind:
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Choice> choiceList = new List<Choice>();
// ... code to fill the list ...
Repeater1.DataSource = choiceList;
Repeater1.DataBind();
}
}
void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
int idx = int.Parse( e.CommandArgument.ToString() );
// this function is called
}
but if i use ITemplate it doesn't work:
<asp:Repeater ID="Repeater1" runat="server" onitemcommand="Repeater1_ItemCommand">
</asp:Repeater>
code behind:
public class MyButtonTemplate : System.Web.UI.ITemplate
{
public void InstantiateIn(System.Web.UI.Control container)
{
Button button = new Button();
button.CommandName = "choice";
button.DataBinding += new EventHandler(Button_DataBinding);
container.Controls.Add(button);
container.Controls.Add(new LiteralControl("<br />"));
}
}
static void Button_DataBinding(object sender, System.EventArgs e)
{
Button button = (Button)sender;
RepeaterItem repeaterItem = (RepeaterItem)button.NamingContainer;
button.ID = "button" + (repeaterItem.DataItem as Choice).id.ToString();
button.CommandArgument = (repeaterItem.DataItem as Choice).id.ToString();
button.Text = (repeaterItem.DataItem as Choice).description;
}
void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Choice> choiceList = new List<Choice>();
// ... code to fill the list ...
Repeater1.ItemTemplate = new MyButtonTemplate();
Repeater1.DataSource = choiceList;
Repeater1.DataBind();
}
}
void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
int idx = int.Parse( e.CommandArgument.ToString() );
// this function is NOT called
}
the buttons are displayed, but the event is not fired.
i have already tried saving a delegate in MyButtonTemplate and assigning the button click event - it does not work.
thank you!

Why does my button control not display in the code behind?

I have the following code in my aspx page:
<asp:Literal ID="ltPost" runat="server"></asp:Literal>
and this in my code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
BindData();
}
}
protected void BindData() {
str.Append(#"<asp:Button ID=*btnEditReply* runat=*server* CssClass=*button-action m-r-5* Text=*Sửa phản hồi* ValidationGroup=*AddSave*/>");
ltPost.Text = str.ToString().TrimEnd(',').Replace('*', '"');
}
I don't understand this; Why won't the button btnEditReply display?
To add a server control, you have to use Controls.Add(). Also, you can't add a button to a literal, so it's better to use a Placeholder.
C#:
Button editButton = new Button();
editButton.ID = "btnEditReply";
editbutton.Text = "Sửa phản hồi";
// .. etc
placeHolder.Controls.Add(editButton);
HTML:
<asp:Placeholder id="placeHolder" runat="server" />
Reference: http://msdn.microsoft.com/en-us/library/kyt0fzt1(v=vs.100).aspx

ASP Dropdown OnSelectedIndexChange event doesn't fire

I've gone through many articles and question about this. But still not found the answer for my case.
The function handles event. It doesn't work at all
My code:
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Popup.aspx.cs"
Inherits="GG.UI.Popup" %>
...
<asp:DropDownList ID="LEDropdown" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="LEDropdown_Change" ></asp:DropDownList>
ASPX.CS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateClist();
BindGrid();
}
}
protected void PopulateClist()
{
LEDropdown.Items.Clear();
LEDropdown.Items.Add(new ListItem("First Item", "First");
LEDropdown.Items.Add(new ListItem("Second Item", "Second");
LEDropdown.SelectedIndex = 0;
}
protected void LEDropdown_Change(object sender, EventArgs arg)
{
string selectedLE = ((DropDownList)(sender)).SelectedValue;
ClientScript.RegisterStartupScript(GetType(), "Alert", "alert('" + selectedLE + "');");
}
I tried using EnableViewState="true" for this page and the Masterpage as well.Didn't work.
The function LEDropdown_Change was never called.
The page is still posted back after selection.
There's another button with OnClick event and it works fine.
<asp:DropDownList ID="LEDropdown" runat="server" AutoPostBack="true" OnSelectedIndexChanged="LEDropdown_Change" ></asp:DropDownList>
Your dropdownlist is calling LEDropdown_Change
But your onchange event is called: LegalEntityDropdown_Change

C# - Event handler for dynamic buttons

I have a textbox and submit button created using the design mode.
When the submit button is pressed, it will retrieve the user input from the textbox and then make a query to my database.
It will then display a list of dynamic buttons according to the information retrieved from my database.
However, the event handler for the buttons does not fire when clicked. I guess my problem is the postback but I cannot create those buttons in page_load etc. because I need to get the user input (from the textbox when submit button is pressed) before i can load the buttons.
How can i solve this problem?
Thank you.
Edit (codes):
protected void subBtn_Click(object sender, EventArgs e)
{
//database setup codes
.......
while (reader.Read())
{
Button detailsBtn = new Button();
detailsBtn.Text = reader["fName"].ToString();
//doesn't fire
detailsBtn.Click += new EventHandler(detailsBtn_Click);
memPanel.Controls.Add(detailsBtn);
}
}
Main problem is Postback regenerate dynamic controls on each postback if those controls does not exists.
For quick demo see this code
ASPX CODE
<form id="form1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Panel ID="pnl" runat="server"></asp:Panel>
</form>
ASPX.CS CODE
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
generate();
}
}
public void generate()
{
if (!pnl.HasControls())
{
for (int i = 0; i < 4; i++)
{
Button detailsBtn = new Button();
detailsBtn.Text = "fName" + i.ToString();
detailsBtn.ID = i.ToString();
detailsBtn.Click += new EventHandler(detailsBtn_Click);
pnl.Controls.Add(detailsBtn);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
generate();
}
protected void detailsBtn_Click(object sender, EventArgs e)
{
}
Sound to me like you could easily refactor your page to use a simple <asp:Repeater runat="server" ..></asp:Repeater> instead of dynamically adding controls to a Panel.
Here is a very simple complete sample:
RepeaterTest.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
<asp:TextBox ID="theTextBox" runat="server"></asp:TextBox>
<asp:Button ID="theButton" runat="server" OnClick="theButton_Click" Text="Click me" />
<asp:Repeater ID="test" runat="server">
<ItemTemplate>
<asp:Button ID="theRepeaterButton" runat="server" Text='<%# Eval("fName") %>' OnClick="theRepeaterButton_Click" />
</ItemTemplate>
</asp:Repeater>
</asp:Content>
RepeaterTest.aspx.cs
public partial class RepeaterTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void theButton_Click(object sender, EventArgs e)
{
string filter = theTextBox.Text;
// below row simulates fetching data using the filter text in the text box
var data = Enumerable.Range(0, 20).Select(i => new { fName = filter + " " + i });
test.DataSource = data;
test.DataBind();
}
protected void theRepeaterButton_Click(object sender, EventArgs e)
{
var button = (Button)sender;
// do something here based on text/commandname/commandargument etc of the button
}
}

Multiple Button in a single view

I have a web project which includes two button in a view.when i click a button some textboxes along with that second button have to be visible.After entering data in textboxes,when i am trying to click the second button, its not working.What should i do to make it work?
Thanks in advance.
Rahul try this
In aspx page
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" />
In aspx.cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Button2.Visible = false;
TextBox1.Visible = false;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Button2.Visible = true;
TextBox1.Visible = true;
}
protected void Button2_Click(object sender, EventArgs e)
{
TextBox1.Text = "Testing";
}

Resources