ASP.Net Button and the onclick event don't work - c#

I make a dynamic table with buttons in they cells, but when i click some button show me this error in console:
Uncaught ReferenceError: bttn_Click is not defined
at HTMLUnknownElement.onclick (VM51 panel.aspx:1)
this is how i make the button in html and asp.net :
StringBuilder htmlStr = new StringBuilder();
htmlStr.Append("<asp:button onclick='bttn_Click' class='btn btn-warning btn-xs' ID='Bttn_PDF'>PDF</asp:button>");
PlaceHolder1.Controls.Add(new Literal { Text = htmlStr.ToString() });
and the C#
protected void bttn_Click(object sender, CommandEventArgs e)
{
Button btn = (Button)sender;
string btnid = btn.CommandArgument;
test.Text = btnid;
}

This is because the onclick event actually expects a Javascript-specific event to be called and you are currently trying to call a server-side event instead. When defining such an event on an actual ASP.NET Button control, you instead want to use the OnClientClick event instead. But this doesn't really matter as you want to target a server-side event and not a client-side one.
Build Your Button Server-side
What you'll likely want to do is create an actual Button control, define a click event handler that points to your method, and then add that control to the page as opposed to building a string:
// Build your button with its specific properties
Button button = new Button();
button.ID = "Bttn_PDF";
button.CssClass = "btn btn-warning btn-xs";
// Wire up its click event
button.Click += bttn_Click;
// Add it to the form
PlaceHolder1.Controls.Add(button);

Related

WPF dynamically add button + function

I wanted to ask you. I am writing a WPF program where I had a problem and had to ask you for advice. How can I dynamically add a button to a WPF window? Again, how can I assign the value of button_click inside the button by giving it a function. Thanks everyone in advance
You can use this
Button b = new Button();
b.Content = "some text"
//set other properties in a similar way
b.Click += (sender,e) => {/* your click handeler*/}
container.Children.Add(b);
where container is a Grid or something similar that you want to add your button to.
You can follow the steps below.
private void SomeEvent(object sender, RoutedEventArgs e)
{
//Your code here
}
Button newBtn = new Button(); //Initialize the button object
newBtn.Content = "Name"; //Give the poor button some text
newBtn.Click += SomeEvent; //Add a click event handler. It is a function which the button will perform when clicked.
MainGrid.Children.Add(newBtn); //Now add the button to your container. It could be a grid panel, stack panel or any other container.
You can also apply padding or margin to further control how the button appears. But that's optional. Cheers!

C# Dynamic RadioButton in Update Panel is not firing on first click?

I have a number of radio buttons created dynamically inside a loop and added to a div inside update panel. On each postback request triggered by checked change event, I recreate the radio buttons in my page_init method. My problem is the radio button I selected is not checked and the checked changed event is not firing on first click. But on subsequent clicks, it works normally and the checked changed event is fired. Only the first click is not firing. What could be the issue?
Simple dynamic radio button.
RadioButton btn2 = new RadioButton();
btn2.Text = "TEST";
btn2.CheckedChanged += Btn2_CheckedChanged; ;
btn2.AutoPostBack = true;
pricetbldiv.Controls.Add(btn2);
private void Btn2_CheckedChanged(object sender, EventArgs e)
{
RadioButton btn = (RadioButton)sender;
string text = btn.Text;
}
Try to assign group and ID
btn2.ID = "Text";
btn2.Text = "Text";
btn2.GroupName = "RB";
btn2.CheckedChanged += new EventHandler(Btn2_CheckedChanged);

Dynamically created image button click event is not fired

On dynamically created table based on some condition i've added imagebutton dynamically. parallelly i want to add event for this image button click but the click event is not getting fired. here is my code snippet.
private void createTable()
{
TableRow tableRow = new TableRow();
TableCell ImageCell = new TableCell();
ImageButton imgBtndeleteAttr = new ImageButton();
imgBtndeleteAttr.ID = "imgbtn_" + i.ToString() + j.ToString();
imgBtndeleteAttr.CssClass = "deleteDynamic";
imgBtndeleteAttr.OnClientClick = "javascript:return confirm('Do you want to delete this Attribute?');";
imgBtndeleteAttr.Click += new System.Web.UI.ImageClickEventHandler(imgBtndeleteAttr_Click);
ImageCell.Controls.Add(imgBtndeleteAttr);
tableRow.Cells.Add(ImageCell);
}
and here is the event
protected void imgBtndeleteAttr_Click(object sender, ImageClickEventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), "lnk",
"<script type = 'text/javascript'>alert('Image button Clicked');</script>");
}
Its a bad idea to use dynamic controls in asp. The controls have to be recreated on postback. So if you create a button dynamically and click it, postback happens and event is triggered but due to postback the button which triggered the event is destroyed and the raised event is discarded.

If I cannot use C# to respond in realtime to radio button CheckedChanged events in Sharepoint, how can I add client-side (jQuery) code to do it?

I posed a similar question about this before, and it would seem based on the answers that I received that I can't expect to be able to rely on a radio button's CheckedChanged event to fire in real time.
Am I really stuck with waiting until the form is submitted before that event fires, or can I add client-side (jQuery) code to handle it? If so, how? How can I mix jQuery client code in with my C# server code in a Sharepoint (2010) project?
What I want to be able to do now is to dynamically alter the controls on the page based on decisions made by the user (if they select this radio button, a particular textbox has this set of properties applied, and if the other radio button, a different set of properties). Is this possible?
UPDATE
I create controls and add CheckedChanged events to them like so:
rbUSCitizenOrPermResY = new RadioButton
{
CssClass = "finaff-webform-field-input"//,
//CheckedChanged += new EventHandler(rbUSCitizenOrPermResY_Changed) <= the name 'CheckedChanged' does not exist in the current context
};
rbUSCitizenOrPermResY.CheckedChanged += new EventHandler(rbUSCitizenOrPermResY_Changed);
cellRadioButton1_1.Controls.Add(rbUSCitizenOrPermResY);
The Save button is like so:
Button btnSave = new Button();
btnSave.Text = "Save";
btnSave.Click += new EventHandler(btnSave_Click);
this.Controls.Add(btnSave);
. . .
private void btnSave_Click(object sender, EventArgs e)
{
LiteralControl message = null;
try
{
message = new LiteralControl();
Controls.Add(message);
ConditionallyCreateList();
SaveInputToList();
List<ListColumns> listOfListItems = ReadFromList();
GeneratePDF(listOfListItems);
message.Text = "Saving the data and converting it to a PDF has been successful";
}
catch (Exception ex)
{
message.Text = String.Format("Exception occurred: {0}", ex.Message);
}
}
What is special about the Save button that it fires immediatley when clicked, yet the CheckedChanged event of a RadioButton does not fire (immediately)?
UPDATE 2
This says, "...UpdatePanel control ... by default, this control does not work with these standard SharePoint components..."
So it sounds like using it is trying to shoehorn a lumberjack's foot into a baby booty.
Then what is the preferred method for getting Sharepoint components to update?
UPDATE 3
Theoretically, it seems maybe this will work:
UpdatePanel up = new UpdatePanel();
up.Controls.Add(dynamicTable); // or just add the radio buttons, rather than the entire HtmlTable?
ScriptManager sm = new ScriptManager();
sm.EnablePartialRendering = true;
...I'll find out, I reckon...

Postback from Dynamic Content

I am dynamically building some HTML content on a WebForms page, using HtmlGenericControl().
HtmlGenericControl p = new HtmlGenericControl("p");
// ...
ListItems.Controls.Add(p);
But now I need to add a button to the paragraph created above, and the button needs to do a postback when clicked.
Must I completely rework this code to load child controls, which can contain real server-side buttons? Or is there a way to inject buttons capable of some type of postback?
Here's a test method and test EventHandler that, if called, will add a button control with a server-side Click event to ListItems. The commented-out code will change the markup of the ListItems object if InnerHtml is available but I rethought that approach and assumed the existence of a textbox on the page that would show the results of the click event firing. There are a number of concerns that you'll want to handle if you need those child controls to be present from one postback to another, though- for instance, if Test() isn't called every time the page loads that button won't be created and there will be no way to call its EventHandler unless other controls also call it.
public void Test()
{
System.Web.UI.HtmlControls.HtmlGenericControl p = new System.Web.UI.HtmlControls.HtmlGenericControl("p");
p.InnerHtml = #"<strong>Test</strong>";
// ...
ListItems.Controls.Add(p);
Button b = new Button();
b.ID = "cmdTest";
b.Text = "Test";
b.Click += new EventHandler(test_Click);
p.Controls.Add(b);
}
protected void test_Click(object sender, EventArgs e)
{
// ListItems.InnerHtml = "Test button clicked";
txtTestResults.Text = "Test button clicked at " + DateTime.Now.ToShortTimeString();
}

Categories