Dynamic radio button value retrieval - c#

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

Related

Accessing Properties of checkbox from link button of another page in ASP.NET

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;
}
}

Call code behind method from aspx

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

How To Pass Textbox Value Present In UserControl To Aspx Page Label By Clicking Button In UserControl

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.

ASP.NET Button event is not raised in Web User Control

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.

Ext.Net Button Event not firing

I am using Ext.Net and I have a problem.
I am creating dynamic buttons. It is working but if i click, the button event is not working.:(
How can I fix it?
My code:
foreach (var events in eventsInformation)
{
Ext.Net.Button btn = new Ext.Net.Button();
btn.ID = events.EvtId.ToString();
btn.Text = events.EvtName;
btn.Click += new EventHandler(Tickets_click);
ViewPort1.Controls.Add(btn);
}
There are a couple things that require correction in the original sample:
By default, Ext.NET Button Components do not AutoPostBack (ie, reload the entire page). It is encouraged to use DirectEvents (Ajax call) if you want to communicate with the server and avoid a complete page reload.
Ext.NET Components should be added to the parent .Items Collection, instead of the .Controls Collection.
Here's a complete demo with both these corrections.
Example
<%# Page Language="C#" %>
<%# Register assembly="Ext.Net" namespace="Ext.Net" tagprefix="ext" %>
<script runat="server">
protected override void OnInit(EventArgs e)
{
Ext.Net.Button btn = new Ext.Net.Button();
btn.Text = "Submit (AutoPostBack)";
btn.Click += Button1_Click;
// 1. Set to AutoPostBack, default is "false"
btn.AutoPostBack = true;
// 2. Add Button to .Items Collection
this.ViewPort1.Items.Add(btn);
base.OnInit(e);
}
protected void Button1_Click(object sender, EventArgs e)
{
X.Msg.Notify("Server Time", DateTime.Now.ToLongTimeString()).Show();
}
</script>
<!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>Ext.NET Example</title>
</head>
<body>
<form runat="server">
<ext:ResourceManager runat="server" />
<ext:Viewport ID="ViewPort1" runat="server" />
</form>
</body>
</html>
Now, I'd recommend changing your AutoPostBack Button Click event to a DirectEvent Click. That would require making the following three revisions to the code-behind.
Example
<script runat="server">
protected override void OnInit(EventArgs e)
{
Ext.Net.Button btn = new Ext.Net.Button();
btn.Text = "Submit (DirectEvent)";
// 2. CHANGE to .DirectClick
btn.DirectClick += Button1_Click;
// 3. REMOVE btn.AutoPostBack = true;
this.ViewPort1.Items.Add(btn);
base.OnInit(e);
}
// 3. CHANGE "EventArgs" to "DirectEventArgs"
protected void Button1_Click(object sender, DirectEventArgs e)
{
X.Msg.Notify("Server Time", DateTime.Now.ToLongTimeString()).Show();
}
</script>
Hope this helps.
Use Ext.net DirectMethod instead of ASP.NET postback event handler.
<ext:Button ID="Button1" runat="server" Text="Click Me" Icon="Lightning">
<Listeners>
<Click Handler="Ext.net.DirectMethods.SetTimeStamp();" />
</Listeners>
</ext:Button>
<script runat="server">
[DirectMethod]
public void SetTimeStamp()
{
this.Label1.Text = string.Concat("Server Time: ", DateTime.Now.ToLongTimeString());
}
The place to start is the ASP.NET Page Life Cycle Overview. If you're programatically adding controls to an asp.net page then you should familiarise yourself with it, if you're not already =)
Now work your way down this checklist:
Are you always adding the components (buttons in this instance) to the page? If you don't add them *always, then on post-back they won't be there for the EventHandler to be wired up to, for the handler to fire. (This may not apply to an Ext.Net button triggered by a DirectEvent, but it can't hurt).
Do you have the "usual" Ext.Net handler/module registrations in your web.config file to enable the direct events to be handled?
Have you verified that you're not receiving any javascript client-side errors that are inhibiting the event handler?
Use something like Fiddler to verify that the event is actually triggering a DirectEvent back to the server.
<ext:Button ID="extBtn1" runat="server" Text="Cancel">
<DirectEvents>
<Click OnEvent="extBtn1Click">
<EventMask ShowMask="true" />
</Click>
</DirectEvents>
</ext:Button>
This extBtn1Click event will fire in server-side.
The button is not present when Event is fired. That is why it doesnt work. If you construct some testing button in aspx file, it would work just fine.
Solution: You must construct the button during OnInit event so it will be present, and bound to EventHandler, during the new page cycle after clicking the button.

Categories