How do I go about rendering an asp.net control on a web page from a string in code behind?
For example, say I have the aspx page below:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="nrm.FRGPproposal.Questionnaire1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
//want to render a text box here
</div>
</form>
</body>
</html>
What could I do in my Page_Load event to render a TextBox into the div?
protected void Page_Load(object sender, EventArgs e)
{
//what do i do here to render a TextBox in the div from the aspx page?
}
Caution there may be compilation problems here. But basically add a placeholder control to the code in front as such.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="nrm.FRGPproposal.Questionnaire1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:placeholder id="placeHolder" runat="server"/>
</div>
</form>
</body>
</html>
Then create a TextBox in the code behind programmatically. You will need to include System.Web.UI in order to get the textbox.
Then Add the control to the controls collection on the placeHolder. Set whatever properties you like on the text box programmatically
protected void Page_Load(object sender, EventArgs e)
{
TextBox tb = new TextBox();
placeHolder.Controls.Add(tb); //tb is referring to the name that you want to name your element. in this example given was TextBox. so the name of text box is tb.
}
Easy.
Add two attributes to your div element : <div runat="server" id="myDiv"></div>
Then
TextBox tb = new TextBox();
this.myDiv.Controls.Add(tb);
If you want to render a Custom UserControl you can use the above code
MyUserControl control = (MyUserControl)Page.LoadControl("~/My_VirtualPathToControl");
this.myDiv.Controls.Add(control);
(You must register your control in the aspx file)
One more think.
Be cautious when you execute code on Page_Load event.
You will also need to rebuild the controls in the Page_Init method in order to read the controls' state/values on PostBack.
protected void Page_Init(object sender, System.EventArgs e)
{
TextBox tb = new TextBox();
placeHolder.Controls.Add();
}
Related
I have some Html code that contains the button tag "<button></button>".
I have noticed that if I place a linkbutton inside this element, the postback of the linkbutton will never occur.
So this is not working :
<button><asp:LinkButton ID="lnkExample" OnClick="lnkExampleBtn_Click"runat="server">Text</asp:LinkButton></button>
The server method "lnkExampleBtn_Click" will never be launched.
How come the postback doesn't work ?
Is there a way to have a linkbutton work inside the "button" tag ?
I also tried putting an href element with javascript _doPostback specific method, but that is not working either.
I've tried to reproduce your case.
Here's code behind:
public partial class Test : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnTest_Click(object sender, EventArgs e)
{
lblTest.Text = "Test";
}
protected void btnTest2_Click(object sender, EventArgs e)
{
lblTest.Text = "Test2";
}
}
And here's aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Test.aspx.cs" Inherits="WebApplication1.Test" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LinkButton ID="btnTest" runat="server" OnClick="btnTest_Click">Test</asp:LinkButton>
<button><asp:LinkButton ID="btnTest2" runat="server" OnClick="btnTest2_Click">Test2</asp:LinkButton></button>
<button>test</button>
<asp:Label ID="lblTest" runat="server"></asp:Label>
</div>
</form>
</body>
</html>
What I found is - it depends on browser. In Chrome it's possible to place LinkButton inside tags. In Firefox and IE 10 it's not.
The reason why it's not working is simple - it's not allowed by the HTML 5 standard. You just can't embed a link inside a button.
http://www.w3.org/TR/2011/WD-html5-20110525/the-button-element.html#the-button-element
Link inside a button not working in Firefox
I need to create a radiobuttonlist containing a "other" option, and i have to put a textbox next to it. Here is what i did.
if(!ispostpage){
PlaceofWork.DataSource = workplace;
PlaceofWork.DataBind();
PlaceofWork.DataTextField = "WorkPlace1";
PlaceofWork.DataValueField = "WorkID";
PlaceofWork.Items.Add(new ListItem("Other - Specify<input name=\"OtherWorkPlace\" type=\"text\" value=\"test\" id=\"OtherWorkPlace\"/>", "-1"));
This radiobuttonlist is in a usercontrol.
at the first I didn't add if(!ispostpage) so when i try Request.Form["OtherWorkPlace"], it didn't return anything
after i add the code if(!ispostpage), it pop up the error "Object reference not set to an instance of an object"
So how can I get the value of the input textbox?
Not sure if this would help you out, but wouldn't it help if you place a asp:TextBox control in the page and retrieve the value from it only if 'Other' radio button is checked? This text box can be made visible in the client side once the 'Other' radio button is checked. The text box can be placed next to the radio button using CSS.
You could use a hidden field control on the asp .net side.
<asp:HiddenField runat="server" ID="rbOtherText" />
The set the value of the control using a javascript onblur event.
PlaceofWork.Items.Add(new ListItem("Other - Specify<input name=\"OtherWorkPlace\" type=\"text\" value=\"test\" onblur=\"document.getElementById('" & rbOtherText.ClientID & "').value = this.value;\" />", "-1"));
Then in the code behind just reference the HiddenField.
The runat="server" is not buying you anything, it's probably just being rendered directly into the output. If you can see it when you View Source on the page, then it's not being processed as a server side control. I would get rid of that.
Add an ID attribute with the same value as the name attribute:
PlaceofWork.Items.Add(new ListItem("Other - Specify<input id=\"OtherWorkPlace\" name=\"OtherWorkPlace\" type=\"text\" value=\"test\"/>", "-1"));
Remember that IDs must be unique, so you can only have one of these per page without changing the naming convention. Then you are able to see it in the Form collection, as you previously tried.
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<%# Register src="WebUserControl1.ascx" tagname="WebUserControl1" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:WebUserControl1 ID="WebUserControl11" runat="server" />
<br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
</div>
</form>
</body>
</html>
ASPX Code behind
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
string result = Request.Form["OtherWorkPlace"].ToString();
}
}
ASCX
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="WebApplication1.WebUserControl1" %>
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
</asp:RadioButtonList>
ASCX Code behind
protected void Page_Load(object sender, EventArgs e)
{
var list = new List<string>();
list.Add("1");
list.Add("2");
list.Add("3");
if (!IsPostBack)
{
RadioButtonList1.DataSource = list;
RadioButtonList1.DataBind();
//RadioButtonList1.DataTextField = "Value";
//RadioButtonList1.DataValueField = "Key";
RadioButtonList1.Items.Add(new ListItem("Other - Specify<input id=\"OtherWorkPlace\" name=\"OtherWorkPlace\" type=\"text\" value=\"test\" />", "-1"));
}
}
If your RadioButtonList is in a UserControl, it sounds like you want to re-use this in multiple places, possibly even on the same page. If so, you are definitely going to have to come up with a way to manage the IDs so they don't conflict.
Suppose i have two text fields in one page, one for name and another one for age.
When i click the submit button those values should appear in another page. Can any one give the example for that one.. i am totally confused.
please help me
Thank you
MSDN has a page on this, How to: Pass Values Between ASP.NET Web Pages:
The following options are available even if the source page is in a different ASP.NET Web application from the target page, or if the source page is not an ASP.NET Web page:
Use a query string.
Get HTTP POST information from the
source page.
The following options are available only when the source and target pages are in the same ASP.NET Web
application.
Use session state.
Create public properties in the source page and access the property values in the target page.
Get control information in the target page from controls in the source page.
For your scenario, it sounds like using POST is the way to go, since you have textboxes on the first page. Example:
First page:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Page 1</title>
</head>
<body>
<form id="form1" runat="server" action="WebForm2.aspx">
<div>
Name: <asp:TextBox ID="tbName" runat="server"></asp:TextBox><br />
Age: <asp:TextBox ID="tbAge" runat="server"></asp:TextBox><br />
<asp:Button ID="submit" runat="server" Text="Go!" />
</div>
</form>
</body>
</html>
Notice the action="WebForm2.aspx" which directs the POST to the second page. There's no code-behind.
Page 2 (receiving page):
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm2.aspx.vb" Inherits="WebApplication2.WebForm2" EnableViewStateMac="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Page 2</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Literal ID="litText" runat="server"></asp:Literal>
</form>
</body>
</html>
Notice the EnableViewStateMac="false" attribute on the Page element. It's important.
The code-behind, grabbing the values using a simple Request.Form():
Public Class WebForm2
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
litText.Text = Request.Form("tbName") & ": " & Request.Form("tbAge")
End Sub
End Class
That should work... :)
Put this code to your submit button event handler,
private void btnSubmit_Click(object
sender, System.EventArgs e) {
Response.Redirect("AnotherPage.aspx?Name="
+ this.txtName.Text + "&Age=" + this.txtAge.Text); }
Put this code to second page page_load,
private void Page_Load(object sender,
System.EventArgs e) {
this.txtBox1.Text =
Request.QueryString["Name"];
this.txtBox2.Text =
Request.QueryString["Age"]; }
You have a couple of options.
**
1. Use Query string.
(Cons)
- Text might be too lengthy
- You might have to encrypt/decrypt query string based on your requirement
(Pros)
- Easy to manage
2. Use Session
(Cons)
- May increase processing load on server
- You have to check and clear the session if there are too many transactions
(Pros)
- Values from different pages, methods can be stored once in the session and retrieved from when needed
I have a very simple user control in my web site project which has public property declarations as following
public DateTime StartDate
{
get
{
return _startDate;
}
set
{
_startDate = value;
}
}
public DateTime EndDate
{
get
{
return _endDate;
}
set
{
_endDate = value;
}
}
When i drag the ascx file to one of my aspx page and when i go to code behind of aspx page i can access the controls properties through intelisense, but when i run the project through visual studio i get error "The name 'uctTest1' does not exist in the current context " any suggetions to fix the error?
This is the line where Error shows when i run the project uctTest.StartDate = DateTime.Now;
aspx page markup :
<%# Page Language="C#" AutoEventWireup="true" CodeFile="removetest.aspx.cs" Inherits="removetest" %>
<%# Register src="~/uctTest.ascx" tagname="testCtl" tagprefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<uc1:testCtl ID="uctTest1" runat="server" />
</div>
</form>
</body>
</html>
aspx page code behind :
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
uctTest1.StartDate = DateTime.Now;
}
}
protected void btnEdit_Click(object sender, EventArgs e)
{
}
It seems that you are missing the #Register directive in the .aspx file referring to path of .ascx control.
http://msdn.microsoft.com/en-us/library/c76dd5k1(v=vs.71).aspx
I had another aspx page with different file name in the website project that another developer had copied from my aspx page which had same <%# Page Language="C#" AutoEventWireup="true" CodeFile="aspxpagename.aspx.cs" Inherits="aspxpageClass" %> directive in that copied page. Even though that copied paged didnt have user control strangely page I was working reported the error. Changing that page directive's codefile,inherits attributes to different values fixed the issue.
I'm specifying my doctype as xhtml strict, but it's being sent over the wire as a content type of text/html. I'd like to specify that the content type is application/xhtml+xm, but I can't figure out where, or if, I can configure this from within my application
You can specify it in the # page attributes section, like this:
<%# Page ContentType="application/xhtml+xm" %>
...more on MSDN.
In your code behind file, during the Page_Load event, try addind the following code:
Response.Clear()
Response.ContentType = "application/xhtml+xm"
=========aspx===============
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<asp:literal runat="server" id="dt"></asp:literal>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
==============code behind=========
protected void Page_Load(object sender, EventArgs e)
{
this.dt.Text= "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0
Transitional//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">";
}