I am generating dynamic link buttons in c#.At click of any of them,a other function will be call that will show which link button was clicked.But it is not being call at click of any link button.
This is how i am generating it.
Int32 i; //create a integer variable
for (i = 1; i <= 10; i++) // will generate 10 LinkButton
{
LinkButton lb = new LinkButton(); //create instance of LinkButton
lb.Text = Convert.ToString(i) + ""; //LinkButton Text
lb.ID = Convert.ToString(i); // LinkButton ID’s
lb.CommandArgument = Convert.ToString(i); // LinkButton CommandArgument
lb.CommandName = Convert.ToString(i); // LinkButton CommanName
lb.OnClientClick+= new CommandEventHandler(lb_Command); //Create Handler for it.
//type lb.Command += and press double time Tab Key it will generat the lb_Command() code
PlaceHolder1.Controls.Add(lb); // Adding the LinkButton in PlaceHolder
}
This is function code.
void lb_Command(object sender, CommandEventArgs e)
{
Label1.Text = e.CommandName; // will display the which Linkbutton clicked
Label1.Text = "aaaa";
// Response.Redirect(“LnkBtn.aspx?val=” + Label1.Text); // you can also use as QueryString to send values to another page
}
please provide help.
Thanks.
You are using the wrong event :
ClientClick is just a client side event triggered in javascript.
What you want is the Click Event
[...]
lb.Click += new CommandEventHandler(lb_Command); //Create Handler for it.
If you still aren't catching the event, then chances are you are declaring your LinkButton dynamically at the wrong time in the Page Lifecycle (as mentionned by Eoin Campbell in his comments and in his answer).
He links to an article that's really good on the subject, you should read it to understand why you aren't catching the event.
Judging by your comments on your question and on different answers, you are declaring the button in your Page_Load function. That will not work because Page_Load occurs too late in the page lifecycle.
From what I understand, right now you have :
void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
Int32 i; //create a integer variable
for (i = 1; i <= 10; i++) // will generate 10 LinkButton
{
LinkButton lb = new LinkButton(); //create instance of LinkButton
lb.Text = Convert.ToString(i) + ""; //LinkButton Text
lb.ID = Convert.ToString(i); // LinkButton ID’s
lb.CommandArgument = Convert.ToString(i); // LinkButton CommandArgument
lb.CommandName = Convert.ToString(i); // LinkButton CommanName
lb.OnClientClick+= new CommandEventHandler(lb_Command); //Create Handler for it.
PlaceHolder1.Controls.Add(lb); // Adding the LinkButton in PlaceHolder
}
}
}
You need to get rid of that. Instead, use :
void Page_Init(object sender, EventArgs e)
{
Int32 i; //create a integer variable
for (i = 1; i <= 10; i++) // will generate 10 LinkButton
{
LinkButton lb = new LinkButton(); //create instance of LinkButton
lb.Text = Convert.ToString(i) + ""; //LinkButton Text
lb.ID = Convert.ToString(i); // LinkButton ID’s
lb.CommandArgument = Convert.ToString(i); // LinkButton CommandArgument
lb.CommandName = Convert.ToString(i); // LinkButton CommanName
lb.OnClientClick+= new CommandEventHandler(lb_Command); //Create Handler for it.
PlaceHolder1.Controls.Add(lb); // Adding the LinkButton in PlaceHolder
}
}
The article linked above will explain why that is. It's a hard concept to grasp but a very important one.
You are mixing client and server side code. OnClientClick is method for attaching client side code. lb_Command runs on the server side.
Use Click instead.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.onclientclick.aspx
versus
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.click.aspx
Ok. two things. as others have pointed out you should be using the LinkButton Command or Click handlers.
But your second problem is that you are running into Page Life Cycle issues by attempting to only generate your controls
on if(!Postback)
in the Page_Load.
Read this: It's a very good article on the subject that dates all the way back to .net 1
https://web.archive.org/web/20210330142645/http://www.4guysfromrolla.com/articles/092904-1.aspx
In a nutshell, you should be creating your controls every single time (not just on the initial post) and you need to wire up your event handler (the += part) early enough in the page lifecycle such that the events are wired, by the time the PageLifeCycle attempts to trigger them.
Override the page's OnInit method and move your code there, without the if(!Postback) check
Instead of the below code
lb.OnClientClick+= new CommandEventHandler(lb_Command); //Create Handler for it.
use the following
lb.Command+= new CommandEventHandler(lb_Command); //Create Handler for it.
Here is the full code. It running at my end.
protected void Page_Load(object sender, EventArgs e)
{
Int32 i; //create a integer variable
for (i = 1; i <= 10; i++) // will generate 10 LinkButton
{
LinkButton lb = new LinkButton(); //create instance of LinkButton
lb.Text = Convert.ToString(i) + " "; //LinkButton Text
lb.ID = Convert.ToString(i); // LinkButton ID’s
lb.CommandArgument = Convert.ToString(i); // LinkButton CommandArgument
lb.CommandName = Convert.ToString(i); // LinkButton CommanName
//lb.Click += lb_Click; //Create Handler for it.
lb.Command += lb_Command;
//type lb.Command += and press double time Tab Key it will generat the lb_Command() code
form1.Controls.Add(lb); // Adding the LinkButton in PlaceHolder
}
}
void lb_Command(object sender, CommandEventArgs e)
{
Label1.Text = e.CommandName; // will display the which Linkbutton clicked
}
Thanks.
If link button is inheriting from Button class then you should attach to the OnClick event. ?
http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.buttonbase.click(v=vs.100)
or
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.onclick.aspx
Related
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.
I have a string in my main body that takes from an array. I want to pass that to the click event on a linkbutton. Is there any way to do this? Any help much appreciated.
Example code below:
(main body)
string myLabelsName = column.ToString();
LinkButton myButton = new LinkButton();
myButton.Text = ("THIS IS MY BUTTON");
myButton.Click += new System.EventHandler(myButton_Click);
(event)
protected void myButton_Click(object sender, EventArgs e)
{
I WANT THE STRING 'myLabelsName' Here <<
Response.Redirect(myLabelsName + ".aspx");
}
You can use fields/properties or more appropriate here: the LinkButton's CommandName property.
string myLabelsName = column.ToString();
LinkButton myButton = new LinkButton();
myButton.Text = "THIS IS MY BUTTON";
myButton.CommandName = myLabelsName;
myButton.Click += new System.EventHandler(myButton_Click);
// ...
protected void myButton_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton) sender;
string myLabelsName = btn.CommandName;
Response.Redirect(myLabelsName + ".aspx");
}
By the way, you're using a LinkButton, why don't you use it's PostBackUrl property directly?
I have to display n grids, n is variable, then I dont know how many grids I'll have.
My problem is, I have to init this grids with Visible false and when click in a button show the grid specific for that button, then how can I link a button to a gridview?
My code that generate the grids:
foreach (List<DataRow> lst in grids)
{
dt = lst.CopyToDataTable();
GridView grv = new GridView();
grv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromName("#cccccc");
grv.HeaderStyle.BackColor = System.Drawing.Color.Gray;
grv.ID = "grid_view"+i;
grv.Visible = false;
grv.DataSource = dt;
grv.DataBind();
Label lblBlankLines = new Label();
lblBlankLines.Text = "<br /><br />";
Label lblTipo = new Label();
string tipoOcorrencia = lst[0]["DESC_OCORRENCIA"].ToString();
tipoOcorrencia = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(tipoOcorrencia);
int quantidade = lst.Count;
lblTipo.Text = tipoOcorrencia + ": " + quantidade;
LinkButton lkBtn = new LinkButton();
lkBtn.ID = "link_button"+i;
lkBtn.Text = "+";
place_grids.Controls.Add(lblBlankLines);
place_grids.Controls.Add(lkBtn);
place_grids.Controls.Add(lblTipo);
place_grids.Controls.Add(grv);
place_grids.DataBind();
i++;
}
Thanks in advance.
Modify your foreach loop as below.
private void GenerateControls()
{
int i = 0;
foreach (List<DataRow> lst in grids)
{
dt = lst.CopyToDataTable();
GridView grv = new GridView();
grv.AlternatingRowStyle.BackColor = System.Drawing.Color.FromName("#cccccc");
grv.HeaderStyle.BackColor = System.Drawing.Color.Gray;
grv.ID = "grid_view" + i;
//grv.Visible = false;//Commented as the grid needs be generated on client side, in order to make it visible from JavaScript/jQuery
grv.Attributes.Add("style", "display:none;");
grv.DataSource = dt;
grv.DataBind();
//Adding dynamic link button
LinkButton lnkButton = new LinkButton();
lnkButton.Text = "button " + i;
//lnkButton.Click += new EventHandler(lnkButton_Click);
lnkButton.ID = "lnkButton" + i;
lnkButton.OnClientClick = "ShowGrid('" + grv.ClientID + "');";
Label lblTipo = new Label();
lblTipo.Text = "text " + i;
lblTipo.ID = "lbl" + i;
tempPanel.Controls.Add(lblTipo);
tempPanel.Controls.Add(grv);
tempPanel.Controls.Add(lnkButton);
tempPanel.DataBind();
i++;
}
}
Then you will have to add a link button click event as below, if you want server side event to fire. (Un-comment the line where event handler is assigned to link button.)
protected void lnkButton_Click(Object sender, EventArgs e)
{
LinkButton lnkButton = (LinkButton)sender;
String index = lnkButton.ID.Substring(lnkButton.ID.Length - 1);
GridView grv = (GridView)tempPanel.FindControl("grid_view" + index);
grv.Visible = true;
}
You will need to add all dynamically added controls in the Page_Init event for maintaining their state. Refer below links can be useful.
Dynamically Created Controls losing data after postback
ViewState in Dynamic Control
Call method GenerateControls from Page_Init event as below.
protected void Page_Init(object sender, EventArgs e)
{
GenerateControls();
}
EDIT :
JavaScript function...
function ShowGrid(gridID) {
document.getElementById(gridID).style.display = ''
}
I have kept the server side click event as it is. But I have commented the line where the event handler is assigned to the link button.
I'm currently having a problem with event handlers assigned in the code-behind not appearing in the HTML code of the .aspx page. Below is the code fragment that does that:
HtmlTable table = new HtmlTable();
HtmlTableRow row = new HtmlTableRow();
foreach(XmlNode item in IDList)
{
LinkButton btn = new LinkButton();
btn.Text = item.InnerText;
btn.Click += new EventHandler(btn_Click);
HtmlTableCell cell = new HtmlTableCell();
cell.Controls.add(btn);
row.cells.add(cell);
}
table.rows.add(row);
Something like that, more or less. So when I run the page and inspected the buttons using FireBug, I noticed that the eventhandler names for the buttons created have been changed to the LinkButtons' unique ID(ct125, 126, 127, etc), I think, and not "btn_Click"
I'm hoping to hear if anyone else has faced this problem before and found a solution for it. Thanks.
your buttons might be using submit behavior for your buttons. Try setting "UseSubmitBehavior=false" for the buttons.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.button.usesubmitbehavior.aspx
When creating controls dynamically, you should assign them Id also, otherwise asp.net will auto-assign them ids like ctl{somenumber}. Also, you need to recreate these controls on each postback, otherwise your eventhandlers will not work.
I was able to get this code to work as expected. I dynamically add 4 LinkButtons and wire the Click event to a function btn_Click. When I click each link, they call the btn_Click method server-side:
protected void Page_Load(object sender, EventArgs e)
{
HtmlTable table = new HtmlTable();
HtmlTableRow row = new HtmlTableRow();
for (int loop = 1; loop < 5; loop++)
{
LinkButton btn = new LinkButton();
btn.Text = "Test " + loop.ToString();
btn.Click += new EventHandler(btn_Click);
HtmlTableCell cell = new HtmlTableCell();
cell.Controls.Add(btn);
row.Cells.Add(cell);
}
table.Rows.Add(row);
// Add the table to a placeholder.
phInputs.Controls.Add(table);
}
protected void btn_Click(object sender, EventArgs e)
{
// Do something to catch a breakpoint.
var x = 10;
}
Ok, I got it fixed, but I'm absolutely bewildered at why it got fixed this way.
{
HtmlTable table = new HtmlTable();
HtmlTableRow row = new HtmlTableRow();
int btnIndex = 0;
foreach(XmlNode item in IDList)
{
LinkButton btn = new LinkButton();
btn.Text = item.InnerText;
btn.Click += new EventHandler(btn_Click);
btn.ID = "Btn_Page" + btnIndex.ToString();
HtmlTableCell cell = new HtmlTableCell();
cell.Controls.add(btn);
row.cells.add(cell);
}
table.rows.add(row);
}
protected void Btn_Page_0(object sender, EventArgs e)
{
whatever eventhandler code
}
When I inspected the HTML again, the names of the event handler assigned to the buttons are still being changed to its ID.
<a id="Btn_Page_0" href="javascript:_doPostback('Btn_Page_0','')">
So for each of those buttons, their event handlers are changed to Btn_Page_0, Btn_Page_1, Btn_Page_2, etc.
Strange thing is, they all go back to the Btn_Page_0 event handler when clicked, instead of btn_click
So.....yeah. Kinda boggles my mind why it worked like this, but it works anyhow...
We are creating dynamic text boxes and buttons inside a grid for each row. Now we want to create click event for each button. To create button inside the grid in using ITemplate.
Code:
ImageButton imbtnAdd = new ImageButton();
imbtnAdd.ID = "imbtn" + columnName;
imbtnAdd.ImageUrl = "btn_add_icon.gif";
imbtnAdd.Width = 20;
container.Controls.Add(imbtnAdd);
Error:
I have used imbtnAdd.Click += new ImageClickEventHandler(imbtnAdd_Click); but it shows an error message
imbtnAdd_Click does not exist
ImageButton imbtnAdd = new ImageButton();
imbtnAdd.ID = "imbtn" + columnName;
imbtnAdd.ImageUrl = "btn_add_icon.gif";
imbtnAdd.Width = 20;
imbtnAdd.Click += imbtnAdd_Click;
container.Controls.Add(imbtnAdd);
// ...
private void imbtnAdd_Click(object sender, EventArgs e)
{
// handle event
}
Jrista's answer is correct.
Although, if you want to implement different handlers for all the buttons and you are using .Net 3.0 or above, you can use lambdas:
imbtnAdd.Click += (object sender, EventArgs e) =>
{
// Code handling code goes here...
};