Problems adding asp:button to panel using C# - c#

I'm listing the contents of my basket by adding fresh HTML to a panel so it lists it on the aspx page. I'm also trying to add an asp:button at the end which will allow users to remove the items, however the button isnt showing!
Code;
string sHTML = #"<div class='item_bar'>
<div class='item_id'>" + id + #"</div>
<div class='item_title'>" + name + #"</div>
<div class='item_price'>" + cost + #"</div>
<asp:Button class='button' Text='Remove' runat='server' CommandArgument='"+name+#"' OnClick='removeItem' />
</div>";
basketDiv.Controls.Add(new LiteralControl(sHTML));
thanks

If you are going to add controls such as the ASP:BUTTON, you would need to add them not via string but actually doing it
this.pnlFrame.Controls.Add(new Button() {
ID = "buttonId1",
Text = "Text for new button"
});
Keep in mind that this needs to be registered when the page is actually being compiled so that is why it is not working in your case.
Check this link also Adding button to panel dynamically and getting it's parent ID
If you do not want events being captured at runtime, and would like to do the actions via jquery, you can add it using string like you are doing, and add a normal HTML input with type submit
<input type='submit' value='New button'/>
However then when clicked, you need to create scripts on the client side to capture those events.

Create button and then set the properties u want then add in panel
// add the litenal control - DIVs
basketDiv.Controls.Add(new LiteralControl("<div class='item_bar'><div class='item_id'>" + id + "</div><div class='item_title'>" + name + "</div><div class='item_price'>" + cost + "</div>"));
// create button and Add it to basketDiv
Button button = new Button();
button.Name = "Button1";
// you can added other attribute here.
button.Text = "New Button";
button.Location = new Point(70,70);
button.Size = new Size(100, 100);
basketDiv.Controls.Add(button);
// close the parent Liternal "DIV class='item_bar'"
basketDiv.Controls.Add(new LiteralControl("</div>"));

Related

c#-adding a ASP:Button in the back code

Hi it just so happens that I have to need this kind of approach (or any suggestion if you have)
this code produce table
while (rd.Read())
{
resultsHtml.Append("<tr class='odd gradeX'>");
resultsHtml.Append("<td>" + rd["region_location"].ToString() + "</td>");
resultsHtml.Append("<td>" + rd["region_tag"].ToString() + "</td>");
resultsHtml.Append("<td class='center'>");
resultsHtml.Append("<div class='tooltip-demo'>");
resultsHtml.Append("<a class='btn btn-info' href='regionEdit.aspx?id=" + rd["region_id"].ToString() + "'><i class='fa fa-paw'></i></a> ");
resultsHtml.Append("<asp:Button ID='btnDelete' runat='server' Text='Login' CssClass='btn btn-outline btn-primary' Style='width: 100px;' OnClick='btnDelete_Click' />");
resultsHtml.Append("</div>");
resultsHtml.Append("</td>");
resultsHtml.Append("</tr>");
}
if you will notice there is an asp:button there. because i want that if the user clicks that button, it will just delete it. So I put an
public void btnSubmitDelete_Click(object sender, EventArgs e)
{
}
but the things is. It is not displaying and I can't figure out how to put the region_id in the asp:button to determine which is which to delete and every loop of the while. Please help
i think when u want to add an asp control and show that control to end user u should add dynamically control to a placeholder or panel like this code :
<asp:PlaceHolder runat="server" ID="_plchControles"></asp:PlaceHolder>
and in code bihind :
var btn = new System.Web.UI.WebControls.Button();
btn.Text = "sample";
btn.ID = "btnSubmitDelete";
btn.OnClientClick += btnSubmitDelete_Click;
_plchContent.Controls.Add(btn);
Your script will work as HTML control and you can bind click event from Javascript. To do so define a WebMethod in c# and call it from Javascript click event.
e.g.
$("#btnDelete").on("click",function(e)
{
var para=[]
para.param1=val1;
para.param2=val2;
$.post("/path/delete",para,function(result)
{
});
});
C#
[WebMethod]
public void delete(string param1,string param2)
{
//Delete code here
}
else
mohammadreza izadi answers will work if you want to asp.net control but you have to make object of button as defined not string.

how to apply CSSClass & style in while create asp button using StringBuilder in c#

My Code is below which is not working for applied css for created control at client side when applying it,
my css class is : img-rounded
string strClass = "img-rounded", strColor="Green";
StringBuilder sb = new StringBuilder();
sb.Append("<asp:Button OnClick=\"Button1_Click\" runat=\"server\" ID=\"Btn1\" CssClass=\"" + strClass + "\" BackColor=\"" + strColor + "\">" + cellData + "</asp:Button><br />");
First of all you cannot add a <asp:Button as a string to the page and expect it to work. If you want to add true asp buttons dynamically you have to take a different approach:
Button button = new Button();
button.CssClass = strClass;
button.BackColor = System.Drawing.Color.Green;
button.ID = "Btn1";
button.Text = cellData;
button.Click += new EventHandler(Button1_Click);
PlaceHolder1.Controls.Add(button);
Or you could still add a "normal" HTML button to the page, but then you have to use class= instead of CssClass=, which is an attribute of most asp controls (just as BackColor).
sb.Append("<input type=\"button\" onclick=\"Button1_Click()\" id=\"Btn1\" class=\"" + strClass + "\" value=\"" + cellData + "\"><br />");
Note that the OnClick is now a javascript call with () at the end. Of course it will not fire an event in code behind.
Manish that is not how you add an asp button, this article explains how to do it. http://www.aspsnippets.com/Articles/Dynamic-Controls-Made-Easy-in-ASP.Net.aspx
Once you create the button in the code behind then you can access all its properties including cssclass.

c# Webbrowser How to select an added dom element (form hidden button) and invoke a click on the button

Simply,
I am trying to add a form tag, with a hidden and a submit button to a web page loaded in a webbrowser in c#. After I add it I want to invoke the click event on the button.
I do not have a lot of code to show as I was unable to even get close. I could not find an example of this in google.
I have tried to use create element, then InsertAdjacentElement, which seems to work when I examine HtmlDoc, but when i try to get the element by ID it always returns null.
System.Windows.Forms.HtmlDocument doc = harvester.Document;
string ftm = "<form Id = 'SD' method='POST' action='day.cfm'><input type='hidden' name='Day' value='" + selDay + "'><input id='SubmitDay' type='submit' value='View the Schedule'></form>";
var divElem = doc.CreateElement("div");
divElem.InnerText = ftm;
divElem = doc.Body.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterBegin, divElem);
HtmlElement button = doc.GetElementById("SubmitDay");
// button = null, always.
Thanks for any help.
Image shows the DOM after inserting the form.
So here is the code working...
FYI: selDay and wordDay are just string vars containing dates
System.Windows.Forms.HtmlDocument doc = harvester.Document;
const string quote = "\"";
string ftm = "<form Id = 'SD' method='POST' action='schedule.cfm'><input type='hidden' name='Day' value=" + quote + selDay + quote+ ">" + wordDay + "<input id='SubmitDay' type='submit' value='View the Schedule'></form>";
var divElem = doc.CreateElement("div");
divElem.InnerHtml = ftm;
divElem = doc.Body.InsertAdjacentElement(HtmlElementInsertionOrientation.AfterBegin, divElem);
HtmlElement button = doc.GetElementById("SubmitDay");
button.InvokeMember("click");
Based on the screenshot, you are attempting to inject HTML into the page by setting the InnerText property. From the MSDN documentation for this property:
If you attempt to assign HTML to an element with InnerText, the HTML code will display as literals in the document, just as if you were viewing HTML within a text file.
This means that your form and input elements are being injected into the page escaped -- <form> instead of <form>, so when you search the DOM for the button it doesn't exist.
Try using InnerHtml instead.
I'd handle this problem a bit differently. Rather than trying to create an HTML document using .NET HtmlElements, I would simply construct a string variable that contains my web page content. As part of that, I would create a short javascript, that would be triggered when the page is opened (that way you don't need the submit button).
Lastly, after the page is complete, I'd open it a browser object, and it'll do it's thing.
Alternatively, you can use the HttpPost (https://msdn.microsoft.com/en-us/library/microsoft.activities.messaging.httppost(v=azure.10).aspx) class to do the same thing (without having to create a web page).

How to link a div Click to button click server side for dynamic controls

I've got a requirement where I need to be able to click dynamically generated div's
So,I've generated buttons also dynamically and want to link the ClickEvent of Button to div's Click event.
for (int i = 0; i < DtUsers.Rows.Count; i++)
{
ASPxButton btnButton = new ASPxButton();
btnButton.ID = "btnButton" + (i + 1);
btnButton.Visible = false;
btnButton.Click += new EventHandler(this.btnButton_Click);
btntButton.CommandArgument = DtOnlineUsers.Rows[i]["USER_ID"].ToString();
var divCustomItem = new HtmlGenericControl("div");
divUandMeUsers.Controls.Add(divCustomChatItem);
divCustomItem.Controls.Add(btnButton);
divCustomItem.Attributes.Add("onclick", "document.getElementById('<%= " + btnButton.ClientID + " %>').click()");
}
But,it is not working. Can you tell me where I've done wrong?
Is there something I need to do with the UpdatePanel AsyncPostBackTrigger?
When I click the div, in the developer tools, it is saying Uncaught TypeError: Cannot read property 'click' of null
Change
divCustomItem.Attributes.Add("onclick", "document.getElementById('<%= " + btnButton.ClientID + " %>').click()");
to
divCustomItem.Attributes.Add("onclick", "document.getElementById('" + btnButton.ClientID + "').click()");
You don't need the client side server includes during a server side operation.
Edit: OK so I've gone through your code with a finer toothed comb and I've found these additional problems:
The button's visibility is set to false so it won't even be rendered. If you want it to be clickable then you will need to hide it using css visibility.
What is an ASPxButton? Did you mean Button?
As there is nothing in the div its auto height and width will be set to zero.
Try sorting out those issues and post your new code if this still does not work.

Move button into Div

I need to move this new button into this DIV that already exists. This seems to me like it should work but doesn't. What am I doing wrong?
Button button5 = new Button();
button5.Text = "Five";
button5.CssClass = "buttonCSS";
button5.Click += new EventHandler(button5_Click);
button5.ID = "button5";
this.Controls.Add(button5);
string myscript = #"
var navFooter = document.getElementById('NavFooter');
var button5 = document.getElementById('button5');
navFooter.Controls.Add(button5);
";
Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", myscript, true);
I know the two objects are being found. Any ideas?
(Note: I cannot use jQuery.)
Thank you.
Controls.Add() is C#, not JavaScript. To append an element to another element with JavaScript, use appendChild():
navFooter.appendChild(button5);
Why are you doing this through javascript?
If you change the containing <div> to a <asp:Panel>, then you can add the newly created button straight into this panel. The <asp:Panel> is rendered simply as a <div> html element, and you can add the CssClass to this to keep the styles the same.
Gives you overall greater control on the server side and you don't need to worry about the javascript. Especially since you are doing server side work anyway.
Just add runat="server" to the div, and add it in the code behind:
<div id="dvButtonContainer" runat="server" ... >
Another option is to use a Panel, as it outputs a div anyway:
<asp:Panel ID="dvButtonContainer" runat="server" ... >
And in the code behind:
Button button = new Button();
dvButtonContainer.Controls.Add(button);
EDIT: Since DIV is not accessible, here is a workaround:
Button Button1 = new Button();
Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript", String.Format("document.getElementById(\"div1\").appendChild({0});", Button1.UniqueID), true);

Categories