Event Control Not working? - asp.net

i careate button control and place in panel but not working?
protected void Button1_Click(object sender, EventArgs e)
{
Button btn = new Button();
btn.Text = "Test button";
Panel1.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}
void btn_Click(object sender, EventArgs e)
{
Response.Write("<script>alert('test')</script>");
}

When you dynamically add controls to your page, you have to re-add them on any subsequent request (postback). The button you added in Button1_OnClick will not automatically be recreated in a subsequent request (e.g. in a postback).
There a lot's of similar questions about this topic, where you can find details. For examples, use the following search:
https://stackoverflow.com/search?q=dynamic+control+event+[asp.net]

Make sure you assign an ID to the button, and make sure it's the same everytime you create it.
Create the control in the CreateChildControls overload, adding it once in response to another event isn't going to be enough to keep it on the page.
You're best bet is going to be tracking the whether the button needs to be created or not:
bool CreateButton
{
get
{
if (ViewState["CreateButton"] == null)
return false;
return (bool)ViewState["CreateButton"];
}
set
{
ViewState["CreateButton"] = value;
}
}
override void public CreateChildControls ()
{
panel1.Controls.Clear ();
if (CreateButton)
{
Button btn = new Button();
btn.Text = "Test button";
btn.ID = "CreatedButton"; // Note the ID here...
Panel1.Controls.Add(btn);
btn.Click += new EventHandler(btn_Click);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
CreateButton = true;
EnsureChildControls ();
}
void btn_Click(object sender, EventArgs e)
{
Response.Write("<script>alert('test')</script>");
}
Something like that should work for you...

Related

PageIndexChanging Event in search button in asp.net?

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grid();
}
}
protected void btnsearch_Click(object sender, EventArgs e)
{
objRetailPL.ZoneName = ddlzone.SelectedValue;
//IFormatProvider provider = new System.Globalization.CultureInfo("en-CA", true);
//String datetime = txtdate.Text.ToString();
//DateTime dt = DateTime.Parse(datetime, provider, System.Globalization.DateTimeStyles.NoCurrentDateDefault);
//objRetailPL.date =dt;
DataTable dtsearch = new DataTable();
dtsearch = objRetailBAL.searchzone(objRetailPL);
GVRate.DataSource = dtsearch;
GVRate.DataBind();
}
protected void GVRate_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
try
{
GVRate.PageIndex = e.NewPageIndex;
grid();
}
catch (Exception ex)
{
}
}
I have this code for searching records.And for that grid i added page index,but it is not coming properly.When click on search button it is showing more n of records at that time page index is not working. It is calling First grid before clicking search button..How can I change my code please help me.....
Try this ...
private void grid()
{
if(!string.IsNullOrEmpty(yourSearchTextBox.Text)
{
// Then call search method. Make sure you bind the Grid in that method.
}
else
{
// Normally Bind the Grid as you are already doing in this method.
}
}
you have to check whether there is any search Text or not in that grid() method like...

click on button in asp.net

I am creating a button dynamically and place it in a placeholder as below
<asp:Button ID="generateTableSchema" runat="server" Text="Generate Table" OnClick="generate_Click" />
protected void generate_Click(object sender, EventArgs e)
{
Button button = new Button();
button.Text = "Generate Table";
button.ID = "generateTable";
button.OnClick = hello();
PlaceHolder1.Controls.Add(button);
}
but onclick event is not firing.
this is the error i am getting
System.Web.UI.WebControls.Button.OnClick(System.EventArgs)' is inaccessible due to its protection level
hello is as below...
public void hello()
{
Label1.Text = "heellllllllllo";
}
What's wrong here????
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
else
{
button.Click += ButtonClick;
}
}
#Daren u mean like this...
Because you are adding the button programmatic ally you have to add the event handler.
So this would work..
EDIT
Wrapped the button INSIDE Page_Load
protected void Page_Load(object sender, EventArgs e)
{
Button button = new Button();
button.Text = "Generate Table";
button.ID = "generateTable";
button.Click += hello; /// THIS is the handler
PlaceHolder1.Controls.Add(button);
}
ButtonClick would be the name of your method.
protected void hello(Object sender, EventArgs e)
{
// ...
}
Also, as you're generating this at runtime you need to makesure this gets called on postbacks too.
The OnClick is a protected method. You should use the event Click.
button.Click += new EventHandler(Click);
public void hello(object sender, EventArgs e)
{
Label1.Text = "heellllllllllo";
}
By the way, make sure you create and add the control in every postback, otherwise the event won't work.
Change button.OnClick = hello(); to:
button.Click += new EventHandler(hello);
And change the definition for hello() to:
protected void hello(object sender, EventArgs e)
{
Label1.Text = "heeellllllo";
}
The event is called Click. You need to add the event handler with the correct signature:
button.Click += new EventHandler(hello);
and the signature is:
protected void hello(Object sender, EventArgs e)
{
// ...
}
How to: Add an Event Handler Using Code
Note that you need to recreate dynamical controls on every postback.
You assigning the result of executing hello().
Try assigning:
button.OnClick = hello;
-- edit--
apparantly, that does not clarify your error.
Add the handler to the event handler in stead:
button.Click += hello;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
else if(Page.IsPostBack && Label11.Text=="yes")
{
Button button = new Button();
button.Text = "Generate Table";
button.ID = "generateTable";
button.Click += ButtonClick;
PlaceHolder1.Controls.Add(button);
}
}
setting
Label11.Text = "yes";
in generate_click.
protected void ButtonClick(object sender, EventArgs e)
{
Label1.Text = "heeellllllo";
}

Dropdown selected change event fire on button Click event

I have write the code in .Net. When I click the Buttun then fired below event. Please help how to do this.
protected void ddldesignation_SelectedIndexChanged(object sender, EventArgs e)
{
Code.
}
Check if the button is in the page's form collection, you can use that as a condition to stop your drop down list event firing.
protected void ddldesignation_SelectedIndexChanged(object sender, EventArgs e)
{
bool runEventCode = true;
foreach (string ctl in Page.Request.Form)
{
Control c = Page.FindControl(ctl);
if (c is Button)
{
runEventCode = false;
break;
}
}
if (runEventCode)
{
//Event handler code here
}
}

Control Add PostBack Problem

I Add Control Dynamiclly but; easc Postback event my controls are gone. I Can not see again my controls.
So How can I add control ?
Because you must recreate your controls on every postback,
see this article
Add the controls in the Page's Init event and they will be preserved in viewstate when posting back. Make sure they have a unique ID.
See this link...
ASP.NET Add Control on postback
A very trivial example..
public partial class MyPage : Page
{
TextBox tb;
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
tb = new TextBox();
tb.ID = "testtb";
Page.Form.Controls.Add(tb);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
//tb.Text will have whatever text the user entered upon postback
}
}
You should always assign a unique ID to the UserControl in its ID property after control is loaded. And you should always recreate UserControl on postback.
To preserve posback data (i.e. TextBox'es) you must load UserControl in overriden LoadViewState method after calling base.LoadViewState - before postback data are handled.
Add controls in runtime and save on postback:
int NumberOfControls = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["b1"] = 0;
}
else
{
if ((int)ViewState["b1"] > 0)
{
CreateBtn();
}
}
}
protected void btn1_Click(object sender, EventArgs e)
{
NumberOfControls = (int)ViewState["b1"];
Button b1 = new Button();
// b1.Attributes.Add("onclick", "x()");
b1.Text = "test2";
b1.ID = "b1_" + ++NumberOfControls;
b1.Click +=new System.EventHandler(btn11);
Panel1.Controls.Add(b1);
ViewState["b1"] = NumberOfControls;
}
protected void CreateBtn()
{
for (int i = 0; i < (int)ViewState["b1"];i++)
{
Button b1 = new Button();
// b1.Attributes.Add("onclick", "x()");
b1.Text = "test2";
b1.ID = "b1_" + i;
b1.Click += new System.EventHandler(btn11);
Panel1.Controls.Add(b1);
}
}
protected void btn11(object sender, System.EventArgs e)
{
Response.Redirect("AboutUs.aspx");
}

CheckedChanged event for Dynamically generated Checkbox column in DataGrid(Asp.Net)

I have a datagrid (Asp.Net) with dynamically generated checkbox column..I am not able to generate the checkedChanged event for the checkbox..
Here is my code:
public class ItemTemplate : ITemplate
{
//Instantiates the checkbox
void ITemplate.InstantiateIn(Control container)
{
CheckBox box = new CheckBox();
box.CheckedChanged += new EventHandler(this.OnCheckChanged);
box.AutoPostBack = true;
box.EnableViewState = true;
box.Text = text;
box.ID = id;
container.Controls.Add(box);
}
public event EventHandler CheckedChanged;
private void OnCheckChanged(object sender, EventArgs e)
{
if (CheckedChanged != null)
{
CheckedChanged(sender, e);
}
}
}
and Here is the event
private void OnCheckChanged(object sender, EventArgs e)
{
}
Thanks In advance
When do you add your custom column? If it is on load, then it is too late. Load it on init. I.e. following works with your code:
protected void Page_Init(object sender, EventArgs e)
{
ItemTemplate myTemplate = new ItemTemplate();
myTemplate.CheckedChanged += new EventHandler(myTemplate_CheckedChanged);
TemplateField col = new TemplateField();
col.ItemTemplate = myTemplate;
col.ItemStyle.Wrap = false;
grid.Columns.Add(col);
}
If your checkbox ID's are not being set the same way on every postback, then they can never be connected to the event handlers when it comes time to process the events. Where is your field "id" coming from?

Resources