Ext.Net Button Event not firing - c#

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.

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

Update Main page from user control

I have a grid view in my main page and I display some data for user(using BindGrid method).this grid view has some command buttons for each row that perform some operation like Update. when user clicks on update button I show to him/her a user control to update values.and when user clicks on update I want grid bind to new data(I want call BindGrid for new data). How I can do this and call a method in main page from user control?
Edit 1)
I wrote this code for user control:
public partial class SomeUserControl : System.Web.UI.UserControl
{
public event EventHandler StatusUpdated;
private void FunctionThatRaisesEvent()
{
if (this.StatusUpdated != null)
this.StatusUpdated(new object(), new EventArgs());
}
public void Page_Load(object sender, EventArgs e)
{
//....
}
protected void Button1_Click(object sender, EventArgs e)
{
FunctionThatRaisesEvent();
}
}
and the designer for user control :
<%# Control Language="C#" AutoEventWireup="true" CodeFile="SomeUserControl.ascx.cs" Inherits="SomeUserControl" %>
<asp:Button ID="Button1" runat="server" Text="Update" Height="70px"
onclick="Button1_Click" Width="183px" />
and add this code for main page:
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Unnamed1_Click(object sender, EventArgs e)
{
SomeUserControl userControl = (SomeUserControl)LoadControl("SomeUserControl.ascx");
userControl.StatusUpdated += new EventHandler(userControl_StatusUpdated);
Panel1.Controls.Add(userControl);
}
void userControl_StatusUpdated(object sender, EventArgs e)
{
GetDate();
}
private void GetDate()
{
TextBox1.Text = DateTime.Today.ToString();
}
and designer for main page:
<%# Register src="SomeUserControl.ascx" tagname="SomeUserControl" 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">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="upd1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button runat="server" Text="Add User Control" Height="44px" ID="Nims"
onclick="Unnamed1_Click" Width="133px" />
<asp:Panel ID="Panel1" runat="server" BackColor="#FFFFCC"></asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
but it does not work and nothing happend. even I add break point for click user control button code but it seems that event not raise.
Raise the event from the user control, and handle the event from the main page. Check out this question.
//** EDIT **//
You are adding the user control dynamically on button click. When you click the button on your user control it first will initiate postback on the main page - now your user control no longer exists (which is why the event is not raised). If you change your main page designer to look like this:
<%# Register Src="SomeUserControl.ascx" tagname="SomeUserControl" 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 id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="upd1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button runat="server" Text="Add User Control" Height="44px" ID="Nims"
onclick="Unnamed1_Click" Width="133px" />
<asp:Panel ID="Panel1" runat="server" BackColor="#FFFFCC">
<uc1:SomeUserControl ID="userControl" runat="server" />
</asp:Panel>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
and your code-behind to look like this
protected void Page_Load(object sender, EventArgs e)
{
userControl.StatusUpdated += new EventHandler(userControl_StatusUpdated);
}
void userControl_StatusUpdated(object sender, EventArgs e)
{
GetDate();
}
private void GetDate()
{
TextBox1.Text = DateTime.Today.ToString();
}
you will see what I mean. Try setting breakpoints on the page load events of your main page and your user control to see exactly the order in which things happen.
You can register an event in your user control, raise the event when user clicks on update button and capture that event on the page.
http://codebetter.com/brendantompkins/2004/10/06/easily-raise-events-from-asp-net-ascx-user-controls/
you need to use event handler for that
define event handler in your ascx page
public event EventHandler ButtonClickDemo;
when you are performing update or delete event use following code there for event handler.
ButtonClickDemo(sender, e);
in parent page use following
protected void Page_Load(object sender, EventArgs e)
{
btnDemno.ButtonClickDemo += new EventHandler(btn_Click);
}
the function to bind grid of parent page
protected void btn_Click(object sender, EventArgs e)
{
BindGrid();
}
above code will call BindGrid function of parent page.

Dynamic radio button value retrieval

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

Dynamically create a ASP.net Submit LinkButton using a Panel

I am trying to implement an application which will dynamically create a list with a button next to each item on that list. I am partially able to do this using the Panel control in the aspx page and adding html dynamically in the code behind. I am having problems adding the LinkButton dynamically which will do database work based on which ID it is. Is this even possible with what I have?:
aspx:
<asp:Panel ID="ItemPanel" runat="server">
</asp:Panel>
code behind:
...
StringBuilder sb = new StringBuilder();
string UserID;
while (dr.Read())
{
UserID = Convert.ToInt32(dr["UserID"]);
sb.Append("<div><b class='template'></b>");
//Create LinkButton with event and code behind function
}
ItemPanel.Controls.Add(new LiteralControl(sb.ToString()));
You may want to take a look at this very recent question and if you have additional queries, then edit your question.
Edit (after OP's comment)
The purpose of posting that link was to give you an idea how to create the control dynamically. Since you ask, here's a simple bare-bones ASPX page that creates a LinkButton and attaches an eventhandler for the Click event. Not sure what you mean by "handle changes on the server", though.
<%# Page Language="C#" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
LinkButton lnk1 = new LinkButton();
lnk1.Text = "Click me!";
//lnk1.PostBackUrl = "SomeOtherPage.aspx";
// Use the eventhandler to perform redirection,
// instead of the PostBackUrl to show it works.
lnk1.Click += new EventHandler(lnk1_Click);
// Add control to container:
pnl1.Controls.Add(lnk1);
}
void lnk1_Click(object sender, EventArgs e)
{
Response.Redirect("SomeOtherPage.aspx");
}
</script>
<html>
<head>
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Panel ID="pnl1" runat="server">
</asp:Panel>
</form>
</body>
</html>

Prevent Multi-Line ASP:Textbox from trimming line feeds

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

Categories