how can i force postback within a function?

can someone please tell me how i can force a page postback within a server side function?

public void myButton1_click(object sender, System.EventArgs e)
{
// do something
// do something

// need code here that will force a postback

}
trevorayAsked:
Who is Participating?
 
raterusConnect With a Mentor Commented:
It is essentially going to look like this: (They only thing I'm unsure since I don't work with C# much is actually declaring the event with the params you are going to send in the "public event EventHandler" line)

//In your usercontrol
public event EventHandler TheyClickedIt(object sender, string value);

private void DataGrid1_ItemCommand(object sender, DataGridCommandEventArgs e)
{
      string value = myDataGrid.Items[0].Cells[1].text;

      //raise custom event
      TheyClickedIt(this, value);
}

Then on your aspx page:
private void Page_Load(object sender, System.EventArgs e)
{
     //...Load usercontrol (myUsercontrol)
    //Specify EventHandler in Page to handle Event raised in usercontrol
    myUsercontrol.TheyClickedIt +=new EventHandler(myUsercontrol_TheyClickedIt);      
}

private void myUsercontrol_TheyClickedIt(object sender, string value)
{
      someTextBox.Text = value;
}

--Michael
0
 
praneethaCommented:
what exactly r u trying to do?
0
 
trevorayAuthor Commented:
it's way to complicated to get into. i'd just like to know how force a postback. thanks!
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
praneethaCommented:
so u basically want it to run what is in page_load or anything else..

if so...

you can just put whatever in page_load method in a different method and call it at the button1_click...

0
 
trevorayAuthor Commented:
since you're forcing me to answer your question before you answer mine...

i have an .ascx page that contains a datagrid formated like a pretty dropdownlist. i have an onItemCommand that runs when a user selects an item from this datagrid. in this command i need the value of that was selected stored in a session state, then i need to force a page postback. i need to force this postback because i need  a function to run on the .aspx page that the .ascx page is located on. this function won't run until a value is selected. and since the page_load of the .aspx page runs before the page_load of the .ascx page, i have no way of telling the .aspx page that a value was selected on the .ascx page.
0
 
praneethaCommented:
so i am assuming - whatever function you want to call after onItemCommand would need controls on page1(the page which contains the control) ...



0
 
trevorayAuthor Commented:
yes
0
 
raterusCommented:
Ahh, The correct and better solution for you:

Raise an event in your UserControl that the aspx page will handle.  Just like your DataGrid raises the ItemCommand Event for the UserControl to Handle, now your UserControl needs to raise a custom event you define that your ASPX page will handle. (Make sense?)

http://www.oreilly.com/catalog/progaspdotnet/chapter/ch14.html
Scroll down about 1/3 of the page to "Handling events in VB.NET", there are some C# examples too, but this should get you started.

--Michael
0
 
praneethaCommented:
ok here is a wild idea...hope that works...

can u do Response.redirect("samepagewhichcontainsusrcontrol")..

will it help..

if not let me know i have one more crazy idea
0
 
trevorayAuthor Commented:
no, that's a cheat. i don't want to do a redirect. i'll lose all my viewstates, etc.
0
 
raterusCommented:
no way don't do that!
0
 
raterusCommented:
Here is a C# example of what I said:
http://dotnet.org.za/thea/archive/2004/07/15/2834.aspx
0
 
praneethaCommented:
ok you can refresh a page using javascript in itemcommand....

and i know when u refresh it fires the last fired event again....

so it goes thru postback events again...

and you can check the session variable and put the code in itemcommand in a if loop....

0
 
raterusCommented:
You don't need to be using Session in this example, that is a horrid solution..blah bleck Yuck!
0
 
DotNetLover_BaanCommented:
Hi trevoray ,
if you want to get a clear idea how POSTBACK works, read this: http://www.xefteri.com/articles/dec102002/default.aspx
Force a postback: http://weblogs.asp.net/mnolton/archive/2003/06/04/8260.aspx

-Baan
0
 
ajitanandCommented:
here are the steps for this:

Step 1. Add the following script in the HTML Head Section of your ASPX:
-------------------------------
<SCRIPT LANGUAGE="JavaScript">
var globalFlag = false;
function doThePostback(){
      if(globalFlag) document.forms[0].submit();
}
</SCRIPT>
-------------------------------



Step 2. Add the event in <body> tag of your ASPX as follows:
-------------------------------
<BODY onload="doThePostback()">
-------------------------------




Step 3. In your code make changes as follows:
-------------------------------
public void myButton1_click(object sender, System.EventArgs e)
{
// do something
// do something

Response.Write("<SCRIPT LANGUAGE=JavaScript>globalFlag = true;</SCRIPT>");
}
------------------------------------------

A WebForm Postback will happen, and it will not cause any control event!!



hope this helps.

rgds,
Ajit Anand
0
 
gsiricCommented:

>>i need to force this postback because i need  a function to run on the .aspx page that the .ascx page is located on. this >>function won't run until a value is selected. and since the page_load of the .aspx page runs before the page_load of >>the .ascx page, i have no way of telling the .aspx page that a value was selected on the .ascx page.

Hi,
you are actually doing right thing on the wrong way :)
There is a natural way to do this -> events.


1. declare an event in your user control, and add code to fire event in your Button1_click

   public event EventHandler ValueChanged;

   public void myButton1_click(object sender, System.EventArgs e)
  {
     if (ValueChanged != null)
          ValueChanged(this,new System.EventArgs());
  }

2. Add event handler for ValueChagned event in your aspx page.
   If name of your user control is myusercontrol, and ID of control is "Myusercontrol1"
   code will look like:

 // first define event handler
 // this metod will be called in your aspx page from your user control
  public void OnValueChanged(object source, EventArgs e)
  {
     ...
  }

a ) If you are putting control in DataGrid you need to add this lines of code in OnItemDataBound event

  if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
  {
        myusercontrol c = (myusercontrol) e.Item.FindControl("Myusercontrol1")
        c.ValueChanged += new System.EventHandler(this.OnValueChanged);
  }

b) if you have user control directly on the page you need this:

  // control must be declared
   protected myusercontrol Myusercontrol1;

  // attach event handler in InitializeComponent
  private void InitializeComponent()
  {
    ...
    ...  
    this.Myusercontrol1.ValueChanged += new System.EventHandler(this.OnValueChanged);
  }





0
 
trevorayAuthor Commented:
gsiric ,

i like your suggestion, but it is doing a method that i have been told not to do here at work at the review meeting of my code. basically, i currently have it set up so that i can run a function contained on my .aspx from my .ascx page in the onItemCommand function of my datagrid contained on my .ascx page. I was told that this method is wrong because it is a 'child calling a function on a parent', which is not good for reuse. So I have to avoid all programming where there is a method of a 'child calling a parent'
0
 
trevorayAuthor Commented:
ajitanand, your code does not work. i get a javascript error, invalid pointer. plus, from looking at the logic of the code, i can't see how it could possibly work. i understand that when you do the response.write it sets the variable to true, but the page has already loaded by the time the variable is set to true, so the javascript at the beginning of the page will not run until the page is reloaded again.
0
 
raterusCommented:
It doesn't need to work, it is the WRONG thing to do in this situation.  Either listen to gsiric or my suggestions and you won't be banging your head against the wall!

--Michael
0
 
trevorayAuthor Commented:
Michael - i am trying to sort through your suggestions now. i'm trying to sort out all the links and read all the stuff to figure it out. i have a headache today, so thinking is harder for me right now. but, i know that i can't do the whole 'child talking to the parent' thing,  so that's why gsiric's suggestion didn't work for me.
0
 
raterusCommented:
"i know that i can't do the whole 'child talking to the parent' thing"

Why can't you do this?
0
 
trevorayAuthor Commented:
my development team lead doesn't like it. he says that it restricts complete re-use of this usercontrol. which i see his point.
0
 
raterusCommented:
I think you are misunderstanding the suggestion.  Raising events is how the .net CLR works.  Controls raise events which their parent container(control) can handle.  It's why when your datagrid raises that ItemCommand event you can choose to handle it or just let it pass.  This is the SAME concept here, only you are creating your own event for your UserControl to raise.  There is nothing non-reusable about it, if a parent aspx page doesn't care about the event, it doesn't have to do anything about it.  This is how you are supposed to do it, if you've never done it at first it probably is a little confusing, but believe me if you opt to do something crazy like set session variables or postback the page you might as well mark a spot on the wall and start banging your head against it.  :-)

--Michael
0
 
trevorayAuthor Commented:
ok, but if i have a function on my container page, the .aspx page, called myFunction and then on my user control, .ascx page, i have a datagrid with an on ItemCommand and in the ItemCommand, I run the myFunction contained on the .aspx page, then everytime I re-use this user control, I would have to make sure that there is a function on the parent page called "MyFunction". Isn't this correct? This is what they didn't want me to do.
0
 
raterusCommented:
No, this isn't what I'm talking about.  The usercontrol just raises events, events you define, it doesn't actually call the function on the container page.  Your Container page handles this event and calls whatever it wants.  The usercontrol doesn't have to know anything about the parent.

--Michael
0
 
trevorayAuthor Commented:
ok, then i need to read on and see if i can figure this out...
0
 
trevorayAuthor Commented:
ok raterus,

i copied all the code from that O'Reily article and applied it to my page but i still don't get anything. I think it has to do with the fact that the example in the article is based off of a dropdownlist and it's OnSelectedItemIndexChange event, while I am using a datagrid and the selectedITemindex doesn't change on my onItemCommand, so i'm really at a loss on how to proceed and translate the example to my real working code.
0
 
raterusCommented:
It doesn't matter if you are using the Datagrid and examples use DropDownList, you are just dealing with events, and those are all basically the same.

Did you look at gsiric's code again?  I'm assuming it works.  Also take a look at this article
http://dotnet.org.za/thea/archive/2004/07/15/2834.aspx

I'm don't program in C# so I can't really say if they work (most examples do work), but if you have any questions let me know.

--Michael
0
 
trevorayAuthor Commented:
gsiric,

perhaps you could help me out? my user control contains a customized datagrid. the datagrid is named DataGrid1 and the user control is named Select_version.ascx  The datagrid has an onItemCommand designated as "DataGrid1_ItemCommand"

I need to somehow once something in my datagrid has been selected, (thus firing the DataGrid1_ItemCommand function), for the page to post that information back to the .aspx page.

I am at a loss on how to translate above code to get this to work. My user control isn't in a datagrid, but rather my datagrid is in my user control.

I need my .aspx page to take the value of a cell from my datagrid (this value: myString = e.Item.Cells[0].Text;) and apply this value to a function on my .aspx page.
0
 
raterusCommented:
post snippets of your code in usercontrol/web form and I'll do it for you just so you can see what needs to be done.  For the usercontrol, post your ItemCommand Sub and show the value you want to pass back.
0
 
trevorayAuthor Commented:
this is code on my user control named: select_version_datagrid.ascx

public void DataGrid1_ItemCommand(object sender, DataGridCommandEventArgs e)
{
  myString = e.Item.Cells[0].Text;
 }


this is the HTML code on my .aspx page:

<%@ Register TagPrefix="uc1" TagName="select_version_datagrid" Src="select_version_datagrid.ascx" %>

<P><BR><uc1:select_version_datagrid id=select_version_datagrid runat="server / ></P>

this is the code-behind on my .aspx page:

protected table_editor_toolkit.select_version_datagrid select_version_datagrid;

need a function on this page that will take the myString value from my user control once the value is determined and run something off of that value. for now, if i could just get a function that does a Response.Write(myString) on my .aspx page i will be happy.

thanks!








0
 
trevorayAuthor Commented:
ok, i have tried to copy your code onto my pages and this is what i have so far...

on my user control, ascx page i have this...

public delegate void ListChangedHandler(object sender, string myString);
public event ListChangedHandler ListChanged;

public void DataGrid1_ItemCommand(object sender, DataGridCommandEventArgs e)
{
  string myString;
  myString = e.Item.Cells[0].Text;
}


my HTML is still the same on my aspx page....
<%@ Register TagPrefix="uc1" TagName="select_version_datagrid" Src="select_version_datagrid.ascx" %>

<P><BR><uc1:select_version_datagrid id=select_version_datagrid runat="server / ></P>



and my code behind on my .aspx page has changed to...

protected table_editor_toolkit.select_version_datagrid select_version_datagrid;

public void select_version_datagrid_ListChanged(string myString)
{
 Label2.Text = "myString";
}


#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
   //
  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
  //
      InitializeComponent();
      base.OnInit(e);
}
            
      private void InitializeComponent()
      {    
      System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();
      this.select_version_datagrid.ListChanged += new System.EventHandler(this.select_version_datagrid_ListChanged);

      this.Load += new System.EventHandler(this.Page_Load);

      }
#endregion





when i try to do this, i get the error: Select_Version_datagrid_ListChanged(string) does not match the delgate 'void System.EventHandler(object, system.EventArgs)



0
 
gsiricCommented:
Make next modification to ascx.cs:

public void DataGrid1_ItemCommand(object sender, DataGridCommandEventArgs e)
{
  string myString;
  myString = e.Item.Cells[0].Text;

  if (ListChanged != null)
    ListChanged(this,myString);

}

and next to aspx.cs

public void select_version_datagrid_ListChanged(object sender, string myString)
{
 Label2.Text = "myString";
}
0
 
trevorayAuthor Commented:
gsiric,

i made your modifications to my code and am still getting same error i mentioned in my last post.
which is: Select_Version_datagrid_ListChanged(string) does not match the delgate 'void System.EventHandler(object, system.EventArgs)

can someone please help? i'm getting desperate now. thanks!

my code now looks like:

in my ascx.cs...
public class select_version_datagrid : System.Web.UI.UserControl
      {
            protected System.Web.UI.WebControls.DataGrid DataGrid1;
            public delegate void ListChangedHandler(object sender, string myString);
            public event ListChangedHandler ListChanged;

            public void DataGrid1_ItemCommand(object sender, DataGridCommandEventArgs e)
            {
                  string myString;
                  myString = e.Item.Cells[0].Text;

                  if (ListChanged != null)
                        ListChanged(this,myString);
                }


This is the code in my aspx.cs...

public class table_editor : System.Web.UI.Page
      {
            protected table_editor_toolkit.select_version_datagrid select_version_datagrid;

            public void select_version_datagrid_ListChanged(object sender,string myString)
            {
                  Label2.Text = "myString";
            }

#region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            private void InitializeComponent()
            {    
                  System.Configuration.AppSettingsReader configurationAppSettings = new System.Configuration.AppSettingsReader();
                  this.select_version_datagrid.ListChanged += new System.EventHandler(this.select_version_datagrid_ListChanged);    <---------- THIS IS WHERE THE ERROR OCCURS  ------
            
                  this.Load += new System.EventHandler(this.Page_Load);

            }
#endregion


                  
0
 
gsiricConnect With a Mentor Commented:


this.select_version_datagrid.ListChanged += new System.EventHandler(this.select_version_datagrid_ListChanged);    

must be:

this.select_version_datagrid.ListChanged += new table_editor_toolkit.select_version_datagrid.ListChangedHandler(this.select_version_datagrid_ListChanged);    
0
 
trevorayAuthor Commented:
yeah, it works! thanks! i'm going to split between gsiric and raterus b/c raterus gave alot of help too.
0
All Courses

From novice to tech pro — start learning today.