I have the following aspx code where I am calling a method from code behind. The result of the code behind method is not getting rendering in the page.
<%# Page Language="C#" AutoEventWireup="false" Src="LeftMenuSrce.aspx.cs" Inherits="LeftMenuSrce" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head>
<title>Home</title>
</head>
<body>
<asp:Table ID ="LeftMenuTable" runat="server">
<asp:TableRow>
<asp:TableCell ID="LeftMenuSrce" OnDataBinding="_getLeftMenuSrc"></asp:TableCell></asp:TableRow>
</asp:Table>
</body>
</html>
Below is my cs code:
public class LeftMenuSrce : System.Web.UI.Page
{
protected System.Web.UI.WebControls.TableCell LeftMenuSrce;
protected System.Web.UI.WebControls.Table LeftMenuTable;
protected void Page_Load(object sender, EventArgs e)
{
LeftMenuSrce.DataBind();
}
protected string _getLeftMenuSrc()
{
string leftMenu;
leftMenu = "LeftMenuNew.aspx";
return leftMenu;
}
}
Even I have tried div instead of asp:tables, but nothing was working.
<div>
<%#_getLeftMenuSrce()%>
</div>
Any clues to overcome this issue? Thanks in advance.
Please note I have referred below links, but nothing helped me.
How to call a code-behind method from aspx page?
Call code behind method from aspx page
ASP.NET - Use variable in .aspx page
Use <%=_getLeftMenuSrc() %>
You must implement your method "_getLeftMenuSrc()" as an event handler.
Example:
protected void _getLeftMenuSrc(object sender, EventArgs e) {}
I guess you simply try to write some text into your TableCell LeftMenuSrce.
One way to do this is writing a OnPreRender event handler like this:
protected void TableCell1_OnPreRender(object sender, EventArgs e)
{
TableCell1.Text = "My text in a cell !!";
// Hint: 'sender' is your table cell ;-)
((TableCell) sender).Text = "My other text in that cell !!";
}
An other way is to fill all your tables cells within the Page_Load event. Like this:
protected void Page_Load(object sender, EventArgs e)
{
TableCell1.Text = "My text in a cell !!";
}
BTW: Don't use tables to build a navigation ;-). Try this link: http://www.w3schools.com/css/css_navbar.asp
Related
I am creating a web application using asp.net I'd like to know how to alter properties of a checkbox of one page from another page: Eg: my Page2.aspx page has a checkbox with id checkbox1 and by default its visibility is false. Now i need to set the visibility of checkbox1 to true from another page Page1.aspx with click event of a link button with id linkbutton1.
any help in this regards please?
Since the web is stateless, each page within a .NET website or web application loads independently of one another. Therefore, you're not able to directly control elements on one .aspx from another .aspx.
However, you would be able to store the desired settings for a control when Page1.aspx posts back and then use the settings saved from Page1.aspx to load the desired settings when Page2.aspx is loaded.
I'm not a huge fan of using Session management, but something like this would work:
The following event could exist on Page One.
protected void btnPageOne_Click(object sender, EventArgs e)
{
Session["PageTwoIsChecked"] = true;
}
Then when Page Two is loaded, you could check the session information set in Page One.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["PageTwoIsChecked"] != null && Convert.ToBoolean(Session["PageTwoIsChecked"]) == true)
{
chkPageTwo.Visible = true;
}
}
I hope this helps!
You can use this approach also
page1.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:linkbutton ID="Linkbutton1" runat="server" onclick="Linkbutton1_Click">LinkButton</asp:linkbutton>
</div>
</form>
</body>
</html>
page1.aspx.cs
protected void Linkbutton1_Click(object sender, EventArgs e)
{
Response.Redirect("page2.aspx?visible=1");//this is how to control the visibility
}
and page2.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
//Request.QueryString["visible"].ToString() will be same
if (Request.QueryString[0].ToString() != "1")
{
CheckBox1.Visible = false;
}
else
{
CheckBox1.Visible = true;
}
}
TestUC.ascx Design Code
<asp:TextBox ID="txtbox1" runat="server" ClientIDMode="Static" placeholder="Enter Some Text" ></asp:TextBox><br />
<asp:Button ID="btn1" runat="server" Text="Click" OnClick="btn1_Click" ClientIDMode="Static" />
Test.aspx Page Code
<%# Register Src="~/WebUserControls/TestUC.ascx" TagName="WebUserControlTest"
TagPrefix="uctest" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphBody" runat="server">
<asp:Label ID="lbl1" runat="server" >Label</asp:Label>
<uctest:WebUserControlTest ID="ucTest" runat="server"></uctest:WebUserControlTest>
</asp:Content>
OutPut:
I Need ..
Step1: Enter Some text In Text Box
Step2:Then I Click Click Button
[Note: This Two Controls Are Bind From UserControl]
Step3:What Text Entered in TextBox Is Show In label [Note Label Present In Aspx Page]
You will need to have a custom event & you will also need to expose the Text property of the TextBox in your UserControl, like this.
public partial class YourUserControl : UserControl
{
public String Text
{
get
{
return this.txtBox1.Text;
}
//write the setter property if you would like to set the text
//of the TextBox from your aspx page
//set
//{
// this.txtBox1.Text = value;
//}
}
public delegate void TextAppliedEventHandler(Object sender, EventArgs e);
public event TextAppliedEventHandler TextApplied;
protected virtual void OnTextApplied(EventArgs e)
{
//Taking a local copy of the event,
//as events can be subscribed/unsubscribed asynchronously.
//If that happens after the below null check then
//NullReferenceException will be thrown
TextAppliedEventHandler handler = TextApplied;
//Checking if the event has been subscribed or not...
if (handler != null)
handler(this, e);
}
protected void yourUserControlButton_Click(Object sender, EventArgs e)
{
OnTextApplied(EventArgs.Empty);
}
}
Then in your aspx page, where you have placed YourUserControl (OR you are dynamically adding it from the code behind), you can subscribe to this event like this.
protected void Page_Load(Object sender, EventArgs e)
{
if (!IsPostBack)
{
yourUserControl.TextApplied += new YourUserControl.TextAppliedEventHandler(yourUserControl_TextApplied)
}
}
You can use the custom event of the user control in your page like this.
protected void yourUserControl_TextApplied(Object sender, EventArgs e)
{
yourLabelInYourPage.Text = yourUserControl.Text;
}
And you are done...
EDIT : You can rename the Controls & Events as you like. I have used the names only for the example purpose.
EDIT : In website projects, if you want to add your user control dynamically then,
you might need to include the namespace ASP in your page, like this.
using ASP;
And add this Directive in your page in the aspx markup.
<%# Reference Control="~/PathToYourUserControl/YourUserControl.ascx" %>
other solution : create an event in the usercontrol, which is called in the button click.
Subscribe to this event in the codebehind of the aspx page. that way you can update your interface only if a value is provided.
a little more complicated, but you could re-use this logic to more complex control / parent control feature in the future.
i can add code snippet if asked
This Answer Is Prepared By Help Of #Devraj Gadhavi i Edited Some Code .
UserControl Page Design Code
<asp:TextBox ID="txtbox1" runat="server" ClientIDMode="Static" placeholder="Enter Some Text" ></asp:TextBox><br />
<asp:Button ID="btn1" runat="server" Text="Click" OnClick="btn1_Click" ClientIDMode="Static" />
UserControl Page Code
public partial class TestUC : System.Web.UI.UserControl
{
public String Text
{
get
{
return this.txtbox1.Text;
}
}
public delegate void TextAppliedEventHandler(Object sender, EventArgs e);
public event EventHandler TextApplied;
protected virtual void OnTextApplied(EventArgs e)
{
if (TextApplied != null)
TextApplied(this, e);
}
protected void btn1_Click(object sender, EventArgs e)
{
OnTextApplied(EventArgs.Empty);
}
}
Aspx Page Design Code
<%# Register Src="~/WebUserControls/TestUC.ascx" TagName="WebUserControlTest"
TagPrefix="uctest" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphBody" runat="server">
<asp:Label ID="lbl1" runat="server" >Label</asp:Label>
<uctest:WebUserControlTest ID="ucTest" runat="server"></uctest:WebUserControlTest>
</asp:Content>
Aspx Cs File Code
public partial class Test2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ucTest.TextApplied += new EventHandler(ucTest_TextApplied);
}
protected void ucTest_TextApplied(Object sender, EventArgs e)
{
lbl1.Text = ucTest.Text;
}
}
Another method ,If you don't want to expose the Text property of the TextBox in your UserControl Just use method "UserControl.FindControl("Id Of your Textbox which is present in user control")" in your Case WebUserControlTest.FindControl("txtbox1").
And below is the simpler way to register an event handler on the parent web form's code behind.
Code goes as below for parent form asxp.cs
protected override void OnInit(EventArgs e)
{
//find the button control within the user control
Button button = (Button)WebUserControlTest.FindControl("btn1");
//wire up event handler
button.Click += new EventHandler(button_Click);
base.OnInit(e);
}
void button_Click(object sender, EventArgs e)
{
TextBox txt = (TextBox) WebUserControlTest.FindControl("txtbox1");
//id of lable which is present in the parent webform
lblParentForm.Text=txt.text;
}
Also, you can achieve this using JavaScript like below (given your code above):
<script type="text/javascript">
function getUCTextboxValue() {
let txtName = document.getElementById('<%=ucTest.FindControl("txtbox1").ClientID %>');
let lbl = document.getElementById('<%=lbl1.ClientID %>');
lbl.innerText = txtName.value
}
Also, from the parent page, you can add a HiddenField and save the textbox value on it (using the JavaScript code above) then catch its value from code behind.
I have a ASP.NET user control, which contains a Telerik Report Viewer plus a button (server control).
I need to handle some stuff inside the click event of the button, but the event does not seem to fire.
Does anyone know why this is the case?
Here is the HTML directives inside the UserControl:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ReportControl.ascx.cs" Inherits="TelerikReportCustomRetrive.UserControl.ReportControl" %>
Here is the markup inside the UserControl:
<form runat="server" id="form1">
<telerik:ReportViewer ID="ReportViewer1" runat="server" Height="461px" ShowDocumentMapButton="False" ShowHistoryButtons="False" ShowNavigationGroup="False" ShowParametersButton="False" ShowPrintPreviewButton="False"></telerik:ReportViewer>
<asp:Button runat="server" ID="btnNav" OnClick="btnNav_Click" />
And the code behind code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var instanceReportSource = new InstanceReportSource
{
ReportDocument =
new TheReport()
};
ReportViewer1.ReportSource = instanceReportSource;
}
}
protected void btnNav_Click(object sender, EventArgs e)
{
Response.Write("Button Fired!");
}
Delete the if(!PostBack) statement. You should always initialize the control, not only if page is not post back.
this.Controls.Add(new CheckBox{ Checked = true; })
When I add this in the page_load. It works, it adds the checkbox and it is visible.
A little different approach:
var button = new CheckBox{ Checked = true; }
globals.button = button;
this.Controls.Add(button);
Globals is a class with a checkbox property on which I want to set the checkbox in the hope of retrieving it's a data after pressing a button.
public static CheckBox button { get; set; }
However, when a button is pressed, the control has vanished of my screen and the button in my globals class has not been updated with any changes I have made to the checkbox.
How can I change the checked state of a checkbox and catch it's current state when I perform a button.click event?
You must re-create dynamic controls on every postback, they wont magically re-appear because every request is a new instance of the Page class.
See my previous post on this subject, it is using a user control but the idea is just the same.
And another
You must add the control before Page_Load
I normally do it in the overridden CreateChildControls but some people use Page_Init.
see this article
Update
This is a very simple way to add the checkbox dynamically, that preserves state/value when the button is clicked.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
<!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">
<asp:PlaceHolder runat="server" ID="ph"></asp:PlaceHolder>
<asp:Button OnClick="btn_Click" runat="server" ID="btn" Text="Click Me" />
<asp:Label runat="server" ID="lbl"></asp:Label>
</form>
</body>
</html>
Then Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Test : Page
{
private CheckBox MyCheckBox { get; set; }
protected override void CreateChildControls()
{
this.MyCheckBox = new CheckBox() { Checked = true };
this.ph.Controls.Add(this.MyCheckBox);
base.CreateChildControls();
}
protected void btn_Click(object sender, EventArgs e)
{
var someValue = this.MyCheckBox.Checked;
this.lbl.Text = someValue ? "Checked" : "Not Checked";
}
}
If dynamic controls are created in the Page_Load(object sender, EventArgs e) method they will not return the changes the user made.
The reason you're having problems is the ASP.Net view state is created before the Page_Load(object sender, EventArgs e) method is called. The ASP.Net view state hold what controls are on the page and their values. The Page_Init(object sender, EventArgs e) method is called before the ASP.Net view state is created. By creating the controls in the Page_Init(object sender, EventArgs e) method will return what the user enter, furthermore the controls will only need to be created if the page isn't a post back.
If you can't create the controls in the Page_Init(object sender, EventArgs e) method for some reason, you will edit to change the ASP.Net view state the Page_Load(object sender, EventArgs e).
If you need to create the controls in the Page_Load(object sender, EventArgs e) method this question should help How to Persist Variable on Postback
I have the following webform:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="TestWebApp.Default" %>
<!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:TextBox ID="txtMultiLine" runat="server"
Width="400px" Height="300px" TextMode="MultiLine"></asp:TextBox>
<br />
<asp:Button ID="btnSubmit" runat="server"
Text="Do A Postback" OnClick="btnSubmitClick" />
</div>
</form>
</body>
</html>
and each time I post-back the leading line feeds in the textbox are being removed. Is there any way that I can prevent this behavior?
I was thinking of creating a custom-control that inherited from the textbox but I wanted to get a sanity check here first.
I ended up doing the following in the btnSubmitClick()
public void btnSubmitClick(object sender, EventArgs e)
{
if (this.txtMultiLine.Text.StartsWith("\r\n"))
{
this.txtMultiLine.Text = "\r\n" + this.txtMultiLine.Text;
}
}
I must be really tired or sick or something.
I think that the problem here is in the way that the browser renders the textarea contents, not with ASP.NET per se. Doing this:
public void btnSubmitClick(object sender, EventArgs e) {
this.txtMultiLine.Text = "\r\n" + this.txtMultiLine.Text;
}
will let you reach the desired screen output, but you'll add an extra newline to the Text that the user didn't enter.
The ideal solution would be for the TextBox control in ASP.NET to always write the newline AFTER writing the open tag and BEFORE writing the contents of Text. This way, you'd reach the desired effect without trumping the contents of the textbox.
We could inherit from TextBox and fix this by overriding RenderBeginTag:
public override void RenderBeginTag(HtmlTextWriter writer) {
base.RenderBeginTag(writer);
if (this.TextMode == TextBoxMode.MultiLine) {
writer.Write("\r\n"); // or Environment.NewLine
}
}
Now, creating a new class for this small issue seems really overkill, so your pragmatic approach is completely acceptable. But, I'd change it to run in the PreRender event of the page, which is very late in the page lifecycle and would not interfere with the processing of the submitted text in the OnSubmit event of the button:
protected void Page_Load(object sender, EventArgs e) {
this.PreRender += Page_OnPreRender;
}
protected void Page_OnPreRender(object sender, EventArgs e) {
this.txtMultiLine.Text = "\r\n" + this.txtMultiLine.Text;
}