asp.net add link button dynamically click function - c#

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.

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

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

How do I pass a string to an click event in ASP.Net on a LinkButton click? C#

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?

LinkButton Click Event Doesn't Fire

I have created link button from code behind and binded with action like this
but this method Render is never invoked on click event. What I missed here ?
Panel pnlMain = new Panel();
Panel pnlContent = new Panel();
LinkButton lbContent = new LinkButton();
lbContent.Click += new EventHandler(Redirect);
pnlContent.Controls.Add(lbContent);
pnlMain.Controls.Add(pnlContent);
private void Redirect(object sender, EventArgs e)
{
}
Try this,
Panel pnlMain = new Panel();
Panel pnlContent = new Panel();
LinkButton lbContent = new LinkButton();
lbContent.Click += new EventHandler(Redirect);
Redirect(this, EventArgs.Empty);
private void Redirect(object sender, EventArgs e)
{
}
Are you missing runat="server" tag? however the compilator should complain about that.
Try this it will work.
In your aspx page
<form id="form1" runat="server">
<div>
</div>
</form>
And the codebehind:
protected void Page_Load(object sender, EventArgs e)
{
Panel pnlMain = new Panel();
Panel pnlContent = new Panel();
LinkButton lbContent = new LinkButton();
lbContent.Text = "click";
lbContent.Click += new EventHandler(Redirect);
pnlContent.Controls.Add(lbContent);
pnlMain.Controls.Add(pnlContent);
this.form1.Controls.Add(pnlMain);
}
private void Redirect(object sender, EventArgs e)
{
}

Programmatically create asp:Button and attach event in SharePoint

I'm trying to create ASP.NET buttons programmatically inside an update panel in my SharePoint instance, but because of the page life cycle, I can not attach server side events on buttons.
Here is the code:
TableCell tcellbutton = new TableCell();
b.Click += new EventHandler(b_Click);
b.CausesValidation = true;
tcellbutton.Controls.Add(b);
tr.Cells.Add(tcellbutton);
table.Rows.Add(tr);
panel1.Controls.Add(table);
void b_Click(object sender, EventArgs e)
{
string studentnumber = (sender as Button).ID.ToString().Substring(3, (sender as Button).ID.ToString().Length - 3);
TextBox t = panel1.FindControl("txt" + studentNumber) as TextBox;
}
Is there another way to create and attach buttons in Sharepoint?
Ok here is how I solved it, Thanks for all replies, I was looking for a way to attach an event to a button that is created dynamically during runtime (after initialization). Hope It works for others as well.
<script type="text/javascript">
function ButtonClick(buttonId) {
alert("Button " + buttonId + " clicked from javascript");
}
</script>
protected void Button_Click(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), ((Button)sender).ID, "<script>alert('Button_Click');</script>");
Response.Write(DateTime.Now.ToString() + ": " + ((Button)sender).ID + " was clicked");
}
private Button GetButton(string id, string name)
{
Button b = new Button();
b.Text = name;
b.ID = id;
b.Click += new EventHandler(Button_Click);
b.OnClientClick = "ButtonClick('" + b.ClientID + "')";
return b;
}
You should add your code in PreInit event, code below work good:
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
Button bb = new Button();
bb.Click += new EventHandler(bb_Click);
bb.CausesValidation = true;
bb.ID = "button1";
Panel1.Controls.Add(bb);
}
private void bb_Click(object sender, EventArgs e)
{
Response.Write("any thing here");
}
You are creating dynamic controls. Your code should execute in each PageLoad event.
Remove IsPostBack for the part of code where you are creating the buttons is my advice.
If you don't do this, you will create the controls, but each time when PageLoad event occurs, your control will be deleted and the application will not follow your events. With other words you should always recreate the controls.

Categories