I have created a dynamic link button. I want to navigate to other pages when the click event is fired . But now, when I click on the link button, the entire page is cleared off and no click event is fired.
System.Web.UI.WebControls.LinkButton lbView = new System.Web.UI.WebControls.LinkButton();
lbView.Text = "<br />" + "View";
lbView.Click += new System.EventHandler(lbView_Click);
tc.Controls.Add(lbView);
tr.Cells.Add(tc);
protected void lbView_Click(object sender, EventArgs e)
{
Response.Redirect("contactus.aspx");
}
Please help.
When you are creating dynamic control you can not directly create click event of that control. In your case you must follow this way. Add javascript to redirect contactus.aspx page.
System.Web.UI.WebControls.LinkButton lbView = new System.Web.UI.WebControls.LinkButton();
lbView.Text = "<br />" + "View";
btn.OnClientClick = "return RedirectTo();"; // You need to add javascript event
tc.Controls.Add(lbView);
tr.Cells.Add(tc);
// javascript
<script>
function RedirectTo()
{
window.location.href = 'contactus.aspx';
return false;
}
</script>
Try this. Hope it works for you.
Put your code inside like this and try :-
if(!IsPostBack){
System.Web.UI.WebControls.LinkButton lbView = new System.Web.UI.WebControls.LinkButton();
lbView.Text = "<br />" + "View";
lbView.Click += new System.EventHandler(lbView_Click);
tc.Controls.Add(lbView);
tr.Cells.Add(tc);
}
protected void lbView_Click(object sender, EventArgs e)
{
Response.Redirect("contactus.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'm trying to call a function created in code through <asp:Button>'s on click event but its not working...
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ToString());
ArrayList myArrayList = ConvertDataSetToArrayList();
Literal objliteral = new Literal();
StringBuilder objSBuilder = new StringBuilder();
// Display each item of ArrayList
foreach (Object row in myArrayList)
{
objSBuilder.Append("<div class='AppItem'>");
objSBuilder.Append("<label class='control-label span3'>" + ((DataRow)row)["PlanName"].ToString() + "</label>");
objSBuilder.Append("<label class='control-label span3'> Plan Description :" + ((DataRow)row)["PlanDesc"].ToString() + "</label>");
objSBuilder.Append("<label class='control-label span3'> Price :" + ((DataRow)row)["PlanCost"].ToString() + "</label>");
objSBuilder.Append("<label class='control-label span3'> Total Visitors :" + ((DataRow)row)["PlanVisitors"].ToString() + "</label>");
objSBuilder.Append("<div class='control-group'><asp:Button Text='AddtoCart' runat='server' id='" + ((DataRow)row)["PlanId"].ToString() + "' class='btn btn-small btn-success' onclick='AddPlanToCart();' /></div>");
//<asp:Button ID="ImageButton1" runat="server" Text="Upload" CssClass="btn btn-small btn-success" onclick="ImageButton1_Click" />
objSBuilder.Append("</div>");
}
objliteral.Text = objSBuilder.ToString();
PlanContent.Controls.Add(objliteral);
}
private void AddPlanToCart()
{
//This does not get called.
}
Click here to see code behind!
The problem here is that you're generating the code to run on the client-side, but including scripts and tags designed to be run through the asp.net processor:
objSBuilder.Append("<div class='control-group'><asp:Button Text='AddtoCart' runat='server' id='" + ((DataRow)row)["PlanId"].ToString() + "' class='btn btn-small btn-success' onclick='AddPlanToCart();' /></div>");
which produces HTML including [slightly reformatted]:
<div class='control-group'>
<asp:Button ... onclick='AddPlanToCart();' />
</div>
instead of the <button> control that you're obviously expecting.
Fixing this to work in the manner its written in would be a significant amount of work. Instead, I'd strongly recommend rewriting it to use an <asp:repeater> control instead.
Your onclick is attempting to call a javascript function AddPlanToCart(). You have a couple of options. Here's 2:
1) Create a javascript that does a postback with a specific query string. Check for the query string in page_load, if it exists then call the function.
2) Create an actual dynamic control. It should be created in Page_init if you want to track it's viewstate, not Page_load. Then Add an event handler for the button.
Button b2 = new Button();
b2.Text = "Add To Cart";
b2.Click += new EventHandler(AddPlanToCart);
When creating the button, you can also bind the click event, to a delegate like the following:
Button btn = new Button();
btn.Text = "Button text";
btn.AutoSize = true;
btn.Location = new Point(y, 0);
btn.Click += delegate(object sender, EventArgs e)
{
solution.Invoke();
};
In this case I am passing an Action<>, as a parameter within the method. When you click on the button, the delegate would be triggered. For instance, this button would be created, and when clicked, a messagebox would show:
Button btn = new Button();
btn.Text = "Button text";
btn.AutoSize = true;
btn.Location = new Point(y, 0);
btn.Click += delegate(object sender, EventArgs e)
{
MessageBox.Show("Clicked!");
};
For your scenario, try something within these lines:
int counter = 0;
// Display each item of ArrayList
foreach (Object row in myArrayList)
{
Control ctrl = new Control();
Label lbl = new Label();
lbl.Text = "Label " + counter.ToString();
Button btn = new Button();
btn.Text = "Button text " + counter.ToString();
btn.Click += delegate(object sender, EventArgs e)
{
Response.Write("<script>alert('Message for button " + counter.ToString() + "');</script>");
};
ctrl.Controls.Add(lbl);
ctrl.Controls.Add(btn);
counter++;
PlanContent.Controls.Add(ctrl);
}
I was create a button dynamically with event handler. But the event not fired. Please help me to do this. My partial code is here.
Button btn = new Button();
btn.ID = "btn" + i;
btn.Text = "Add New";
Panel1.Controls.Add(btn);
btn.Click += new EventHandler(this.GreetingBtn_Click);
Panel1.Controls.Add(new LiteralControl("<br /><br />"));
void GreetingBtn_Click(Object sender, EventArgs e)
{
create();
}
I want to access the create() function when i click the button.
Without knowing much about your code, I'm guessing you're not creating the control in the appopriate stage of the page life cycle of ASP.NET
what you need is PreInit, as described here:
Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
Create or re-create dynamic controls.
if you are adding this dynamic button on page load, make sure its under
if (!IsPostBack)
{
//add button here
}
always make your code of creating one time control that will made should be in side !ispostback because they are not need to be created again and again
if (!IsPostBack)
{
//Your code should be their enter code here
}
List<string> myControls = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
myControls = new List<string>();
ViewState["myControls"] = myControls;
}
}
protected void override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
myControls = (List<string>)ViewState["myControls"];
foreach(string controlID in myControls){
//method to create your buttons goes here.
createButtons(controlID);
}
}
public void createButtons(string btnID){
Button btn = new Button();
btn.ID = btnID;
btn.Text = "Add New";
btn.Click += new RoutedEventHandler(this.GreetingBtn_Click);
Panel1.Controls.Add(btn);
Panel1.Controls.Add(new LiteralControl("<br /><br />"));
}
void GreetingBtn_Click(Object sender, RoutedEventArgs e){
create();
}
Give this code a try. When adding controls dynamically in asp.net you have to recreate the controls in the postback. The easiest way to do this is using the viewstate as I showed above.
Common signs of not doing this correctly are: control disappears when you click it or event just doesn't fire at all. Hope this helps someone!
Move btn.Click += new EventHandler(this.GreetingBtn_Click); line one level up i.e. before adding to parent And try Routed events.
Button btn = new Button();
btn.ID = "btn" + i;
btn.Text = "Add New";
btn.Click += new RoutedEventHandler(this.GreetingBtn_Click);
Panel1.Controls.Add(btn);
Panel1.Controls.Add(new LiteralControl("<br /><br />"));
void GreetingBtn_Click(Object sender, RoutedEventArgs e)
{
create();
}
I am working on a ASP.NET site, in which i display results returned by internal search engine to the end user. I am parsing the result creating HTML string to display those results as following
foreach (XmlNode result in results)
{
srHtml = "<li class=\"\" style=\"\">";
srHtml += " <span class=\"title\">" + result.SelectSingleNode("./web:Title", nsmgr).InnerText + "</span> <button>Short This URL</button>\n";
if (result.SelectSingleNode("./web:Description", nsmgr) != null)
srHtml += "<br />" + result.SelectSingleNode("./web:Description", nsmgr).InnerText + "<br />";
srHtml += "<span class=\"url\">" + result.SelectSingleNode("./web:Url", nsmgr).InnerText + "</span></li>\n";
phResults.Controls.Add(new System.Web.UI.LiteralControl(srHtml));
}
I can see that button on result page. But I dont know where can I put the code that run when user clicks on this button. When User clicks on that button, I want to change that button textfield with shorten url.
Can anyone help me out here ?
Regards,
Sumit Lonkar
What about doing it this way?:
Button button = new Button();
button.ID = "Button1";
button.Click += new EvandHandler(Button1_Click);
phResults.Controls.Add(button);
And your event handdler:
protected void Button1_Click(object sender, EventArgs e)
{
//Event handler code here
}
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.