Update Main page from user control - c#

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.

Related

Re-Binding Event-Handlers in ASP.NET 4.0 "Templated Control"?

Edit: Sadly, nobody seems to know. Maybe this will help clarify my dilemma: I'm trying to implement my own DataList type of control that supports switching from ItemTemplate to EditItemTemplate. The problem occurs when clicking on a button inside the EditItemTemplate -- it doesn't trigger the handler unless you click a second time!
Sorry about the lengthy post. The code is complete, but hopefully with nothing distracting.
I'm trying to create my own User Control that accepts multiple templates. I'm partly following techniques 39 and 40 from "ASP.NET 4.0 in Practice" by Manning. It seems to be working, except the button inside the template isn't bound to the handler until the second click (after one extra postback).
There are four files involved. Default.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register Src="~/TheTemplate.ascx" TagPrefix="TT" TagName="TheTemplate" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<TT:TheTemplate ID="tt" runat="server">
<ATemplate>
<p>This is template A</p>
<asp:Button ID="TemplateAButton" OnClick="TemplateAButton_Click" runat="server" Text="Template A Button" />
</ATemplate>
<BTemplate>
<p>This is template B</p>
<asp:Button ID="TemplateBButton" OnClick="TemplateBButton_Click" runat="server" Text="Template B Button" />
</BTemplate>
</TT:TheTemplate>
<br />
<asp:Button ID="ToggleTemplate" Text="Toggle Template" OnClick="ToggleTemplate_Click" runat="server" />
</div>
</form>
</body>
</html>
Default.aspx.cs:
using System;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Trace.IsEnabled = true;
tt.DataBind();
}
protected void ToggleTemplate_Click(object sender, EventArgs e)
{
tt.TemplateName = (tt.TemplateName == "A") ? "B" : "A";
tt.DataBind();
}
public void TemplateAButton_Click(object sender, EventArgs e)
{
Trace.Write("TemplateAButton_Click");
}
public void TemplateBButton_Click(object sender, EventArgs e)
{
Trace.Write("TemplateBButton_Click");
}
}
And the user control, TheTemplate.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="TheTemplate.ascx.cs" Inherits="TheTemplate" %>
<p>Using template <asp:Literal Text="<%# TemplateName %>" ID="Literal1" runat="server"></asp:Literal></p>
<asp:Placeholder runat="server" ID="PlaceHolder1" />
And finally, TheTemplate.ascx.cs:
using System;
using System.Web.UI;
[ParseChildren(true)]
public class TheTemplateContainer : Control, INamingContainer
{
private TheTemplate parent;
public TheTemplateContainer(TheTemplate parent)
{
this.parent = parent;
}
}
public partial class TheTemplate : System.Web.UI.UserControl, INamingContainer
{
public string TemplateName
{
get { return (string)(ViewState["TemplateName"] ?? "A"); }
set { ViewState["TemplateName"] = value; }
}
[TemplateContainer(typeof(TheTemplateContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate ATemplate { get; set; }
[TemplateContainer(typeof(TheTemplateContainer))]
[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate BTemplate { get; set; }
protected override void OnDataBinding(EventArgs e)
{
TheTemplateContainer container = new TheTemplateContainer(this);
if (TemplateName == "A")
ATemplate.InstantiateIn(container);
else if (TemplateName == "B")
BTemplate.InstantiateIn(container);
PlaceHolder1.Controls.Clear();
PlaceHolder1.Controls.Add(container);
EnsureChildControls();
base.OnDataBinding(e);
}
}
When you first run it, you will see ATemplate being used:
If you click on the Toggle Template button, all the text is correctly rendered:
But clicking on either "Template A Button" or "Template B Button" will not trigger the OnClick handler on the first try:
It will work on the second click:
Does the problem have to do with where .DataBind() is being called?
I'm not quite sure I understand it, but the problem has to do with how newly-added controls go through the "catch-up" events. Removing PlaceHolder1 and adding it programmatically solves the issue. TheTemplate.ascx becomes:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="TheTemplate.ascx.cs" Inherits="TheTemplate" %>
<p>Using template
<asp:Literal Text="<%# TemplateName %>" ID="Literal1" runat="server"></asp:Literal></p>
... and in TheTemplate.ascx.cs, replace OnDataBinding like this:
protected override void OnDataBinding(EventArgs e)
{
TheTemplateContainer container = new TheTemplateContainer(this);
if (TemplateName == "A")
ATemplate.InstantiateIn(container);
else if (TemplateName == "B")
BTemplate.InstantiateIn(container);
System.Web.UI.WebControls.PlaceHolder PlaceHolder1 = new System.Web.UI.WebControls.PlaceHolder();
//PlaceHolder1.Controls.Clear();
PlaceHolder1.Controls.Add(container);
this.Controls.Clear();
this.Controls.Add(PlaceHolder1);
EnsureChildControls();
base.OnDataBinding(e);
}
In the future, if I ever feel like I need to add controls dynamically, I will also create a PlaceHolder dynamically and use that as the root. When PlaceHolder is populated, I will then add it to the page.

How do I write code to a button which must fire on both events onclick and onclientclick simultaneously with single click

iam writing code for button onclient event with js to print the webpage and onclick event for generating pdf and downloading it ..both must be done in a single action..
but when i cancel print which i onclient click event then oncick event is firing .
<script type="text/javascript">
function PrintPage()
{
window.print();
return true;
}
<asp:Button ID="Button3" runat="server" Text="PTPDF" UseSubmitBehavior="false" OnClick="Button3_Click1" OnClientClick ="javascript:PrintPage();" />
</div>
protected void Button3_Click1(object sender, EventArgs e)
{//here is the code for pdf generation,
this code must get fired automatically after onclient click event without users action}
Below code works perfectly on my end and illustrateson how both OnClick and OnClientClick works at a same time-
ASPX -
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Click.aspx.cs" Inherits="Click" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script language="javascript" type="text/javascript">
function confirmthis()
{
document.getElementById('TextBox2').value = 'onclient works';
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" OnClientClick="return confirmthis();" Text="Click Me" /></div>
</div>
</form>
</body>
</html>
Inline code -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Click : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "OnClick works";
}
}
Please paste the above code at your end and let me know if it still doesn't work.
Thanks!!

ASPX Postback selectedIndexChanged

I am using an combobox with some values and AutoPostBack = true, the page does not refresh.
I have a selectedIndexChanged event as well.
I managed to get the selectedValue and I would like to show this in a TextBox.
In the selectedIndexChanged event I did:
textBox1.Text = selectedValue.ToString();
When I inspect this textbox element with Google Chrome I can see the value is set in the TextBox.
But in the browser the value isn't shown, still an empty TextBox.
Do you guys have any clue why this could happen?
Thanks!
How do you populate items for ComboBox? If dynamically via On-Load event then make sure that method that adds items does not run on PostBack.
Here is your working code buddy.
Don't forget ToString method.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Test2.aspx.cs" Inherits="Test2" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
<asp:ComboBox ID="ComboBox1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ComboBox1_SelectedIndexChanged">
<asp:ListItem>Item1</asp:ListItem>
<asp:ListItem>Item2</asp:ListItem>
<asp:ListItem>Item3</asp:ListItem>
</asp:ComboBox>
<asp:TextBox runat="server" ID="textBox1"/>
</div>
</form>
</body>
</html>
and code
public partial class Test2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Text = ComboBox1.SelectedValue.ToString();
}
}

Client script in Timer is not working

I was just trying to learn some Asp.net Ajax stuff and calling javascript from my C# script.
I have a timer that triggers a method that calls a super simple javascript alert function.
It also updates the time every 10 seconds. Now it looks like my code should work. There are no build errors, no exceptions just it doesn't work. The C# part that updates the time. The javascript does not make the alert.
<%# Page Language="C#" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title></title>
<script runat="server">
protected void Page_load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label1.Text = DateTime.Now.ToString();
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
const string someScript = "alertMe";
Label1.Text = DateTime.Now.ToString();
ClientScript.RegisterStartupScript(this.GetType(),someScript, "alert('I was called from Content page!')", true);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager runat="server"> </asp:ScriptManager>
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Label runat="server" ID="Label1"></asp:Label>
<asp:Timer ID="Timer1" runat="server" Interval="10000" OnTick ="Timer1_Tick"></asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
You need to use ScriptManager instead of ClientScript when you are putting the element that triggers the postback inside an UpdatePanel.
Change your code to:
ScriptManager.RegisterStartupScript(this,this.GetType(), someScript, #"alert('I was called from Content page!');", true);
You forgot a ;
ClientScript.RegisterStartupScript(this.GetType(),someScript, "alert('I was called from Content page!');", true);
Most browsers have an error console of some type that you can see these issues as they occur.

Textbox on TextChanged event giving error!

I have a textbox in my webpage and I want to fire as soon User clicks or enter something on this textbox. Code is working but it is firing when an User hits Enter button. I want it to fire when user types their 1st character. Which event is app for this?
This is my mockup code:
<asp:TextBox ID="txtAgentName" runat="server" OnTextChanged = "txtAgentName_TextChanged"></asp:TextBox>
But when I am running this webpage it is showing me this err:
CS0123: No overload for 'txtAgentName_TextChanged' matches delegate 'System.EventHandler'
I have this on my code behind:
protected virtual void txtAgentName_TextChanged(object sender, EventArgs e)
{
}
Made a breakpoint in in here, and seems like it is firing when I am hitting Enter button. I want to fire when user enter 1st character inside that textbox.
What I am doing wrong here?
your event handler must have this signature
protected void txtAgentName_TextChanged(object sender, EventArgs e)
{
...
}
does it?
<%# Page Language="C#" %>
<script runat="server">
protected void txtSearch_TextChanged(object sender, EventArgs e)
{
lblSearchResults.Text = "Search for: " + txtSearch.Text;
}
</script>
<html>
<head>
<title>TextBox AutoPostBack</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label
id="lblSearch"
Text="Search:"
Runat="server" />
<asp:TextBox
id="txtSearch"
AutoPostBack="true"
OnTextChanged="txtSearch_TextChanged"
Runat="server" />
<hr />
<asp:Label
id="lblSearchResults"
Runat="server" />
</div>
</form>
</body>
</html>
Use javascript's TextBox1.Attributes.Add("OnKeyPress", "GetKeyPress()") and then postback if you wish.

Categories