Why won't my SelectedIndexChanged event fire in Button_Click? - c#

protected void Button1_Click(object sender, EventArgs e)
{
TableRow tb = new TableRow();
TableCell tc = new TableCell();
DropDownList db = new DropDownList();
db.Items.Add("Bangalore");
db.Items.Add("Mandya");
db.Items.Add( "Hassan");
tc.Controls.Add(db);
tb.Controls.Add(tc);
Table1.Controls.Add(tb);
db.SelectedIndexChanged += db_SelectedIndexChanged;
db.AutoPostBack = true;
}
private void db_SelectedIndexChanged(object sender, EventArgs e)
{
label.text = "welcome";
}
When this code executes in the Button1_Click event, db_SelectedIndexChanged doesn't execute. However, when I place the same Button1_Click code block in the Page_Load event, db_SelectedIndexChanged executes.
What may be the reason behind this?

Try to put
db.SelectedIndexChanged += db_SelectedIndexChanged;
db.AutoPostBack = true;
In the Page_Load event.
Don't wrap db.SelectedIndexChanged += db_SelectedIndexChanged; in !Page.IsPostBack as the events need to be wired up on each load

You are creating a dynamic control. The event will not fire unless you create the control in the PreInit method of the page.
protected void Page_PreInit(object sender, EventArgs e)
{
DropDownList db = new DropDownList();
db.Items.Add("Bangalore");
db.Items.Add("Mandya");
db.Items.Add( "Hassan");
db.SelectedIndexChanged += db_SelectedIndexChanged;
db.AutoPostBack = true;
tc.Controls.Add(db);
}
Check Page Life cycle for more info.

protected void Button1_Click(object sender, EventArgs e)
{
TableRow tb = new TableRow();
TableCell tc = new TableCell();
DropDownList db = new DropDownList();
db.Items.Add("Bangalore");`
db.Items.Add("Mandya");
db.Items.Add( "Hassan");
tc.Controls.Add(db);
tb.Controls.Add(tc);
Table1.Controls.Add(tb);
db.SelectedIndexChanged += db_SelectedIndexChanged;
db.AutoPostBack = true;
db_SelectedIndexChanged(null,null); // use this line, i hope it will work now.
}
private void db_SelectedIndexChanged(object sender, EventArgs e)
{
label.text = "welcome";
}
You can try this one.

Related

Dynamically created linkbuttons' common event not firing

Whenever DropDownList SelectedIndexChanged, I am adding LinkButtons as ul-li list in codebehind. Each linkbuttons were assigned with IDs and a common Click event. Problem is code in Click event is not executed or maybe event is not triggered. My code below: [Edit] I tried like this as suggested in other posts (dynamically created list of link buttons, link buttons not posting back)
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
populate();
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
populate();
}
void populate()
{
HtmlGenericControl ulList = new HtmlGenericControl("ul");
panel.Controls.Add(ulList);
foreach (DataRow dr in drc)
{
HtmlGenericControl liList = new HtmlGenericControl("li");
ulList.Controls.Add(liList);
var lnk = new LinkButton();
lnk.ID = dr["col1"].ToString();
lnk.Text = dr["col1"].ToString();
lnk.Click += Clicked;
liList.Controls.Add(lnk);
}
}
private void Clicked(object sender, EventArgs e)
{
var btn = (LinkButton)sender;
label1.Text = btn.ID.ToString();
}
Im missing something. Any help please.
Here the issue is with the ViewState. When the selected index of the dropdownlist changes there is a postback which takes place and the previous state is lost, so at this point you have to maintain the state of the controls.
Now in your code actually the state of the control is lost and so the click event does not fire. So the solution is to maintain the state of the controls.
The Below is a working example, you can just paste it and try.
This is my page load.
protected void Page_Load(object sender, EventArgs e)
{
for (var i = 0; i < LinkButtonNumber; i++)
AddLinkButton(i);
}
Similarly you have to maintain the state of the previously added control like this.
private int LinkButtonNumber
{
get
{
var number = ViewState["linkButtonNumber"];
return (number == null) ? 0 : (int)number;
}
set
{
ViewState["linkButtonNumber"] = value;
}
}
The below is my SelectedIndexChanged Event for the DropDownList
protected void Example_SelectedIndexChanged(object sender, EventArgs e)
{
AddLinkButton(LinkButtonNumber);
LinkButtonNumber++;
}
I have a function which dynamically creates the controls, which is called on the page load and on SelectedIndexChanged.
private void AddLinkButton(int index)
{
LinkButton linkbutton = new LinkButton { ID = string.Concat("txtDomain", index) };
linkbutton.ClientIDMode = ClientIDMode.Static;
linkbutton.Text = "Link Button ";
linkbutton.Click += linkbutton_Click;
PanelDomain.Controls.Add(linkbutton);
PanelDomain.Controls.Add(new LiteralControl("<br />"));
}
And this is the Click event for the LinkButton
void linkbutton_Click(object sender, EventArgs e)
{
//You logic here
}
I solved it using brute code lol.
Since controls' event were not bound on postback then we recreate them on postback. So in my Page_Load I called the module that re-creates the controls, thus binding them to corresponding event. This works, but...
Re-creating these controls create duplicates (Multiple Controls with same ID were found) and you will get into trouble in instances of finding a control by ID like using panel.FindControl.
To remedy this scenario, I put a check if same control ID already existed before recreating them, and voila! It works.
protected void Page_Load(object sender, EventArgs e)
{
populate();
}
void populate()
{
HtmlGenericControl ulList = new HtmlGenericControl("ul");
panel.Controls.Add(ulList);
foreach (DataRow dr in drc)
{
HtmlGenericControl liList = new HtmlGenericControl("li");
ulList.Controls.Add(liList);
if (liList.FindControl(dr["col1"].ToString()) == null)
{
var lnk = new LinkButton();
lnk.ID = dr["col1"].ToString();
lnk.Text = dr["col1"].ToString();
lnk.Click += Clicked;
liList.Controls.Add(lnk);
}
}
}

asp.net add link button dynamically click function

I'm trying to add a LinkButton dynamically
This is the html code:
<div id="resultDivText" runat="server">
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
</asp:PlaceHolder>
</div>
This is the c# code
LinkButton lb = new LinkButton();
lb.Text = songName + "</br>"; //LinkButton Text
lb.ID = song.Key.ToString(); // LinkButton ID’s
lb.CommandArgument = Convert.ToString(song.Key);
lb.CommandName = Convert.ToString(song.Key);
lb.Click += new EventHandler(test_Click);
this.form1.Controls.Add(lb);
PlaceHolder1.Controls.Add(lb);
And this is the "test_Click" function
protected void test_Click(object sender, EventArgs e)
{
showAllSong("let it be");
}
When i run the code it's show me the linkButton list but when i click on it nothing happens.
Try this code ..
static bool enable = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DynamicButton();
}
else if (enable)
{
DynamicButton();
}
}
protected void btnBindMapping_Click(object sender, EventArgs e)
{
enable = true;
DynamicButton();
}
protected void DynamicButton()
{
LinkButton lb = new LinkButton();
lb = new LinkButton();
lb.Text = songName + "</br>"; //LinkButton Text
lb.ID = song.Key.ToString(); // LinkButton ID’s
lb.CommandArgument = Convert.ToString(song.Key);
lb.CommandName = Convert.ToString(song.Key);
lb.Click += new EventHandler(test_Click);
this.form1.Controls.Add(lb);
PlaceHolder1.Controls.Add(lb);
}
protected void test_Click(object sender, EventArgs e)
{
Response.Write("<script>alert('done'); </script>");
}
You code is fine ..it works as expected ..But change this line
this.form1.Controls.Add(lb);
to
this.Controls.Add(lb);
Note:It postback to your server not a client sided event
Since you use CommandName and CommandArgument in the LinkButton, you have to delegate a Command not a Click.
lb.Command += new CommandEventHandler(test_Click);
protected void test_Click(object sender, CommandEventArgs e)
{
Response.Write(e.CommandArgument + "<br>" + e.CommandName);
}
And remove the line this.form1.Controls.Add(lb);
And this is not clear from your question, but you have to create that button every time the page is loaded, and that includes a PostBack.
In give detail you have not mention. when this dynamic button is created.
Because that may create a issue.
If you call your c# code in page load event then it works.
LinkButton lb = new LinkButton();
lb = new LinkButton();
lb.Text = songName + "</br>"; //LinkButton Text
lb.ID = song.Key.ToString(); // LinkButton ID’s
lb.CommandArgument = Convert.ToString(song.Key);
lb.CommandName = Convert.ToString(song.Key);
lb.Click += new EventHandler(test_Click);
this.form1.Controls.Add(lb);
PlaceHolder1.Controls.Add(lb);
if that button create dynamically on oninit or onload event then it works.

assign event to ImageButton.Click from code behind

I want to assign events to each ImageButton from code behind, but i can not find out how to write a proper one.
foreach (string one in urls)
{
ImageButton temIBTN = new ImageButton();
temIBTN.Attributes.Add("Width","265px");
temIBTN.Attributes.Add("Width", "144px");
temIBTN.ImageUrl = one;
temIBTN.Click +=
new EventHandler(setBigPic(sender, e, one));//<---don't know how...
}
protected void setBigPic(object sender, ImageClickEventArgs e,string url)
{
img_Big.ImageUrl = url;
}
Your method signature for the event handler was wrong, and you need to get the ImageUrl from the button that's firing the event. This should do it:
foreach (string one in urls)
{
ImageButton temIBTN = new ImageButton();
temIBTN.Attributes.Add("Width","265px");
temIBTN.Attributes.Add("Width", "144px");
temIBTN.ImageUrl = one;
temIBTN.Click += setBigPic;
}
protected void setBigPic(object sender, ImageClickEventArgs e)
{
img_Big.ImageUrl = ((ImageButton)sender).ImageUrl;
}

Dynamically created Button not calling event c#

Button won't call it's event.
called in another button:
placeHolder.Controls.Add(CreateButton());
create button:
public Button CreateButton()
{
Button btn = new Button();
btn.ID = "id";
btn.Text = "some text";
btn.Attributes.Add("onclick", "return false;");
btn.Click += new EventHandler(btn_Click);
return btn;
}
Functionality:
private void btn_Click(object sender, EventArgs e)
{
// do something.
}
places debug lines to find the source, it's simply not calling btn_Click() when clicked. What's missing?
This code prevents the click event from firing:
btn.Attributes.Add("onclick", "return false;");
Remove this code, or change it to:
btn.Attributes.Add("onclick", "return true;");
EDIT
I am tried this code and it worked correctly. PlaceHolder is in form tag and runat attribute is server:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
placeHolder.Controls.Add(CreateButton());
}
public Button CreateButton()
{
Button btn = new Button();
btn.ID = "id";
btn.Text = "some text";
btn.Click += btn_Click;
return btn;
}
private void btn_Click(object sender, EventArgs e)
{
}

Add control/event dynamically doesn't work

Any help would be appreciated --
here is my aspx code -
<div id="div_Detail" class="div_det" runat="server" />
and in my code behind -
protected void Page_Load(object sender, EventArgs e) {
LoadDetail();
}
private void LoadDetail() {
HtmlTable tbl = new HtmlTable();
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell cell = new HtmlTableCell();
Button bUpdate = new Button();
bUpdate.Text = "Update";
bUpdate.Click += this.Update_Click;
cell.Controls.Add(bUpdate);
row.Cells.Add(cell);
tbl.Rows.Add(row);
div_Detail.Controls.Add(tbl);
}
private void Update_Click(object sender, EventArgs e) {
//Do something
}
I see the button on the page with the correct text. But on clicking that button, Update_Click never gets called.
Am I missing something?
Try giving the button an id. The .NET engine needs IDs on controls during postback to associate the control with a given event delegate.
Edit:
This code works fine:
protected void Page_Load(object sender, EventArgs e) {
LoadDetail();
}
private void LoadDetail() {
HtmlTable tbl = new HtmlTable();
HtmlTableRow row = new HtmlTableRow();
HtmlTableCell cell = new HtmlTableCell();
Button bUpdate = new Button();
bUpdate.Text = "Update";
bUpdate.Click += this.Update_Click;
bUpdate.ID = "btnID";
cell.Controls.Add(bUpdate);
row.Cells.Add(cell);
tbl.Rows.Add(row);
div_Detail.Controls.Add(tbl);
}
private void Update_Click(object sender, EventArgs e) {
//Do something
}
Give the button an Id and everything will work fine.
bUpdate.Id = "btnUpdate";
Try This one may help u
bUpdate.Click += new System.EventHandler(this.bUpdate_OnClick);
protected void bUpdate_OnClick(object sender, EventArgs e) {
}

Categories