Dropdown selected change event fire on button Click event - asp.net

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
}
}

Related

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";
}

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

Can't seem to capture a button click in a gridview in asp.net

I put some Image Buttons into my gridview, but I cannot capture the click event. Neither creating a click event, nor creating an OnRowCommand handler in the gridview works.
Clicking the buttons simply postbacks to the current page.
I add my buttons like this:
protected void gridview1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string status = DataBinder.Eval(e.Row.DataItem, "visitstatusuid").ToString();
string visitUID = DataBinder.Eval(e.Row.DataItem, "visituid").ToString();
Color backColor = Color.White;
Color foreColor = Color.Black;
ImageButton b;
switch (status)
{
case "U": // Unallocated
backColor = ColorTranslator.FromHtml("#B2A1C7");
b = new ImageButton();
b.Width = Unit.Pixel(25);
b.Height = Unit.Pixel(30);
b.AlternateText = "Book";
b.ImageUrl = "../../Images/New/booking.gif";
b.ToolTip = "Booking";
b.CommandName = "Booking";
b.CommandArgument = visitUID;
b.CausesValidation = false;
e.Row.Cells[(e.Row.Cells.Count - 3)].Controls.Add(b);
etc.
You'll need to attach the handler when the button is created:
b.Click += MyButtonClickEventHandler;
Edit:
Instead of creating the button in the OnRowDataBound handler, use OnRowCreated.
This ensures the button is recreated on postbacks.
Example:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
BindData();
}
}
protected void BindData()
{
// Do your databinding here.
}
protected void MyGridView_RowCreated(object sender, GridViewRowEventArgs e)
{
var b = new ImageButton();
b.AlternateText = "Click Me!";
// Etc.
b.Click += MyButton_Click;
// Add the button to the column you want.
}
protected void MyButton_Click(object sender, ImageClickEventArgs e)
{
// Do your thing...
}
Unless you are adding an event handler elsewhere you would need to set AutoEventWireup="true" in the page directive of your aspx file.
That being said I prefer explicitly wiring events so rather than use AutoEventWireup add this line to your OnInit method:
gridview1.RowDataBound += this.gridview1_RowDataBound;
For your approach using RowDataBound to work, you need to rebind the grid on every page load, and ensure you do it no later than OnLoad in the lifecycle, in order for the click event to be registered in time.
An alternative approach I have had success with is to create a new method for doing the DataGrid button setup, e.g.
void PerformConditionalGridFormatting()
{
foreach (GridViewRow row in gvCaseList.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
... Add your buttons to the cells here
}
}
}
Then you call the method every time you perform a manual databind, and also on every postback i.e. in your OnLoad handler do:
if (Page.IsPostBack) PerformConditionalGridFormatting();
The advantage of this approach is that you don't have to databind on every postback, which saves resources.
create a RowCommand event handler for the gridview and check the command name to see if it's your button triggering it
something to the effect of
void gridview1_RowCommand(object sender, args e)
{
if (e.CommandName == "Booking")
{
// call your desired method here
}
}
Put the binding event of grid in to not post back.

Event Control Not working?

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...

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