Get asp.net button html - asp.net

I have mostly worked with MVC but now doung a project in asp.net. I can't figure out how to render an anchor button, link button or whatever from code behind in a block of text. This button will do postback.
Example: The following errors occured, Click Here.
How do you get the html of that button and append it to the text?

You can add a button to placeholder, like this:
In markup, add this:
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
In code, add this:
protected void Page_Load(object sender, EventArgs e)
{
Button btn = new Button();
btn.ID = "myButton";
btn.Text = "Dynamic Button";
btn.UseSubmitBehavior = true;
btn.Click += new EventHandler(myButton_Click);
PlaceHolder1.Controls.Add(btn);
}
And access the button's click event :
protected void myButton_Click(object sender, EventArgs e)
{
// Do whatever you need
}
NOTE: You have to recreate all dynamically created controls after postback! In this example code to create the button is placed in Page_Load so that it will be recreated at each postback.

Related

using AutoPostBack doesn't work when setting input value in JS

I have a custom control which inherits from TextBox.
This allows me to use the TextBox's AutoPostBack property. This property makes the Page_Load method on the parent page fire when I change the value and click out of the text box.
I am setting the value of the rendered text box in JS as follows
var outputData = document.getElementById("CameraScannerTextbox1");
outputData.value = barcode.Value;
When this code runs I am expecting the Page_Load method to run again.
I have tried things like
outputData.focus();
outputData.value = barcode.Value;
outputData.blur();
The code in the Page_Load is
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Label1.Text = CameraScannerTextbox1.Text;
}
}
So basically I am hoping to have whatever is in barcode.Value set on Label1.Text on the server.
All you need is to trigger onchange event for input since ASP.NET adds postback code to onchange attribute. The simplest way is calling onchange manually
var outputData = document.getElementById("CameraScannerTextbox1");
outputData.value = barcode.Value;
outputData.onchange();
For more advanced techniques of simulating onchange event see this and this answers.
You can simply trigger the PostBack yourself with __doPostBack.
<asp:TextBox ID="CameraScannerTextbox1" runat="server" ClientIDMode="Static" AutoPostBack="true"></asp:TextBox>
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
<script>
var outputData = document.getElementById("CameraScannerTextbox1");
outputData.value = '123456';
__doPostBack('CameraScannerTextbox1', '');
</script>
</asp:PlaceHolder>
Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Label1.Text = CameraScannerTextbox1.Text;
PlaceHolder1.Visible = false;
}
}
Not that I placed the javascript in a PlaceHolder that is hiddedn on PostBack, otherwise it will create a PostBack loop. But there are other ways to prevent that also.

how I find a control in datalist

I have taken a datalist in my asp.net project which contains some picture and picture name. Now I want to show each picture in another page after. It means if any user will click on the picture then picture will open with it's details in another page.So I want to know that how I find a control in datalist.
In following picture of datalist I want to click on picture name like Jai Ho and It will open in another page.
You can use the OnClientClick property of Link Button.
In <asp:LinkButton> tag add following code
OnClientClick="javascript:window.open('your_url');"
try this
protected void up-movie-name_Click(object sender, EventArgs e)
{
Label4.Text = (Datalist1.SelectedItem.FindControl("Label1").ToString());
}
or
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item)
{
LinkButton linkButton = e.Item.FindControl("LinkButton1") as LinkButton;
string commandText = linkButton.Text;
}
}

How to move a dynamically created button?

I have a Button1 and a textbox. When i put a value in textbox and click this button then a new button is created with the value filled in textbox but i want that when again i click Button1 and there should be one more button or we can say how to move previous button's position?
This is code for Button1 in .aspx.cs
protected void Button1_Click(object sender, EventArgs e)
{
Button btnNew = new Button();
btnNew.ID = "btnNew";
btnNew.Text = textBox1.Text;
form1.Controls.Add(btnNew);
}
Please help me to solve this.
Thanks in advance.
You could probably do something like this with JavaScript/jQuery:
$('#button1').click(function() {
$('#button2').css('position', 'absolute');
$('#button2').css('top', '50px');
});
etc. You should provide more info as suggested by Matt.

Wiring events on dynamically-loaded ASP.NET User Controls?

For a "dashboard" module I need to dynamically load user controls based on criteria as the user enters the page (role, etc). The problem is that the events are not being fired at all from the controls
As I understand it I need to load the controls in the OnPreInit method of the dashboard page, however I cannot get a reference to the Placeholder control at this point of initialization (i.e. I get a NullReferenceException); trying to load the Placeholder dynamically via Page.FindControl gives me, ironically, a StackOverflowException.
I've tried loading the controls in PreRender and OnInit as well but the events in the controls are not wired up properly and will not fire.
The code is basically this:
// this does not work; if I try to access the placeholder control itself
// ("phDashboardControls") I get a NullReferenceException, if I try
// Page.FindControl("phDashboardControls") I get a StackOverflowException
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
Control ph = Page.FindControl("phDashBoardControls"); // Placeholder
if (ph != null)
{
// GetControlsToLoad just instantiates the controls and returns
// an IList<Control>. Eventually it will have logic to
// determine which control needs to be loaded based on user role etc.
foreach (Control control in GetControlsToLoad())
{
ph.Controls.Add(control);
}
}
}
// IModularControl is a custom interface defining a single
// Initialize method to set up a control...
private void Page_Load(object sender, EventArgs e)
{
foreach (Control control in this.phDashboardControls.Controls)
{
if (control is IModularControl)
((IModularControl)control).Initialize(this.CompanyID);
}
}
I've successfully loaded controls dynamically in Page_Load before. The only thing I found I had to be careful of was to ensure that if I did a postback, the same controls were loaded in subsequent page_load to ensure that the view state didn't get corrupted... all events etc worked as expected. In my case the controls flow ended up something like this:
page_load - load control a
(do something which causes postback and event x to fire)
page_load - make sure you load control a
event_x - clear control a, load control b
(do something which causes postback)
page_load - make sure you load control b
...
it meant loading controls you fully intented discarding, but was the only way I could find to not corrupt the viewstate...
If you have a page with PlaceHolder1 and Label1 in it, then the following code causes the button click event to fire just fine:
protected void Page_Load(object sender, EventArgs e)
{
var dynamicButton = new Button() { Text = "Click me" };
dynamicButton.Click +=new EventHandler(dynamicButton_Click);
PlaceHolder1.Controls.Add(dynamicButton);
}
void dynamicButton_Click(object sender, EventArgs e)
{
Label1.Text = "Clicked button";
}
Behaves the same with a user control:
WebUserControl ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs" Inherits="WebUserControl" %>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Click Me" onclick="Button1_Click" />
WebUserControl code behind:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Clicked Button";
}
parent control that loads the child control:
protected void Page_Load(object sender, EventArgs e)
{
var dynamicControl = Page.LoadControl("~/WebUserControl.ascx");
PlaceHolder1.Controls.Add(dynamicControl);
}
Just FYI the issue had to do with validation; the events weren't firing properly because some of the validation controls (there were a ton) weren't configured to only apply to that control.

Problem getting commandeventargs in command event following re-creationg of controls in postback

I am haveing problems getting the command event args following the second click using the code below.
so - when i process a button click, and generate a new button to replace the one that was there i lose the viewstate on the next button click.
Any suggestions on what I need to do to get this to work? I cannot significantly change the structure as I must generate a variable number of totally un-related buttons in the command handler.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
LinkButton btn = new LinkButton();
btn.ID = "btn1";
this.Panel1.Controls.Add(btn);
btn.Command += new CommandEventHandler(myLinkButton_Command);
}
else
{
LinkButton btn = new LinkButton();
btn.ID = "btn1";
this.Panel1.Controls.Add(btn);
btn.Text = "My Button 1";
btn.CommandArgument = "1";
btn.Command += new CommandEventHandler(myLinkButton_Command);
}
}
void myLinkButton_Command(object sender, CommandEventArgs e)
{
int newArg = Convert.ToInt32(e.CommandArgument) + 1;// empty string on second mouse click
this.Panel1.Controls.Clear();
LinkButton myLinkButton = new LinkButton();
myLinkButton.ID = "btn1";
this.Panel1.Controls.Add(myLinkButton);
myLinkButton.Text = "My Button " + newArg.ToString();
myLinkButton.CommandArgument = newArg.ToString();
}
}
This happens because your panel has a literal control in it. When you add your button the first time, it (the button) is a second control. When you later clear panel's controls collection, it becomes the first control and the viewstate is saved for the first control, which on following postback becomes the literal.
Simply convert
<asp:Panel ID="Panel1" runat="server">
</asp:Panel>
to
<asp:Panel ID="Panel1" runat="server" />
and it will work.
You have forgotten to set the CommandArgument property when you recreate the button in Page_Load.

Resources