Link to home
Start Free TrialLog in
Avatar of graham_ball
graham_ball

asked on

How to persist a radio button until it is changed again

I have two buttons, which dictate the schemas that data is displayed from and added to.
I have the first of them selected at startup as a default.

When I select the second button and add a record, the startup button is re-selected and the original datalist displayed.
How can I set things up so that when I select the second radio button, it stays selected?

Thanks
Avatar of pheine
pheine

tricky without source, but you can check with an if clause like:

<input type="radio" <% IF condition THEN %>checked <% END IF %>name="" value="">

HTML is interpreted from top to bottom - so the second "checked" will make the browser to check the second box
Avatar of graham_ball

ASKER

OK, I've done some more research and it seems that tis should all work automatically via ViewState.
Problem is  - it doesn't !
Apparently, I should have a hidden field inserted into the html of my webform, but there isn't one there.
I've looked at the properties for the webpage and controls and the enableviewstate property is true.
Anyone any idea why this should not be working ?
r u coding in ASP.net or classic ASP .. if ASP.net, then check if viewstate is disabled for the radiobutton .. then check if it disabled for the page (<@ page .... enableviewstate=false ) and if not then check if it is disabled in ur web.config file (under the "page" tag).. if not then check if it disabled in machine.config file ...
ASP.net using Visual studio 2003.
As I said above, I've checked the page and its controls and they are all enabled.
I can't find a page tag in the web.config and I don't know how to get to the machine config.

cheers.
machine.config .. look in C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG ..
>>Apparently, I should have a hidden field inserted into the html of my webform
i assume u mean the HTML source seen from the browser .. if s, i hope u have all the controls within a form tag .. could u please post ur aspx page ... and ur page_load event ...
This is all the work of Visual Studio. I haven't tampered with the HTML at all.

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="Dream_Feedback_Control.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML xmlns:v="urn:schemas-microsoft-com:vml">
      <HEAD>
            <title>WebForm1</title>
            <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
            <meta content="C#" name="CODE_LANGUAGE">
            <meta content="JavaScript" name="vs_defaultClientScript">
            <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
      </HEAD>
      <body MS_POSITIONING="GridLayout">
            </ITEMTEMPLATE>
            <form id="Form1" method="post" runat="server">
                  <asp:label id="Label1" style="Z-INDEX: 101; LEFT: 334px; POSITION: absolute; TOP: 40px" runat="server"
                        Font-Size="Large" Font-Bold="True" Height="21px" Width="271px">Dream Feedback Control</asp:label><asp:dropdownlist id="cboDoctypes" style="Z-INDEX: 102; LEFT: 226px; POSITION: absolute; TOP: 153px"
                        runat="server" Height="24px" Width="89px" EnableViewState="False"></asp:dropdownlist><asp:textbox id="txtDocumentNum" style="Z-INDEX: 103; LEFT: 475px; POSITION: absolute; TOP: 151px"
                        runat="server" Height="24" Width="87px" MaxLength="10" EnableViewState="False"></asp:textbox><asp:label id="Label2" style="Z-INDEX: 104; LEFT: 123px; POSITION: absolute; TOP: 156px" runat="server"
                        Height="10px" Width="103px">Document Type:</asp:label><asp:label id="Label3" style="Z-INDEX: 105; LEFT: 354px; POSITION: absolute; TOP: 156px" runat="server"
                        Height="15px" Width="121px">Document Number:</asp:label><asp:button id="btnAdd" style="Z-INDEX: 106; LEFT: 724px; POSITION: absolute; TOP: 148px" runat="server"
                        Height="27px" Width="97px" BackColor="PaleGreen" Text="Add Item"></asp:button><asp:datagrid id="dgControlItems" style="Z-INDEX: 107; LEFT: 123px; POSITION: absolute; TOP: 206px"
                        runat="server" Height="122px" Width="697px" AutoGenerateColumns="False" BorderStyle="Ridge" EnableViewState="False">
                        <AlternatingItemStyle BackColor="#E0E0E0"></AlternatingItemStyle>
                        <HeaderStyle Font-Bold="True"></HeaderStyle>
                        <Columns>
                              <asp:ButtonColumn Text="Remove" CommandName="Delete">
                                    <ItemStyle ForeColor="#FF3300"></ItemStyle>
                              </asp:ButtonColumn>
                              <asp:BoundColumn DataField="dream_doctype" ReadOnly="True" HeaderText="Document Type"></asp:BoundColumn>
                              <asp:BoundColumn DataField="dream_docnum" ReadOnly="True" HeaderText="Document Number"></asp:BoundColumn>
                              <asp:BoundColumn DataField="action_ind" ReadOnly="True" HeaderText="Action"></asp:BoundColumn>
                              <asp:BoundColumn DataField="request_date" ReadOnly="True" HeaderText="Request Date"></asp:BoundColumn>
                        </Columns>
                  </asp:datagrid><asp:radiobuttonlist id="optSystem" style="Z-INDEX: 108; LEFT: 206px; POSITION: absolute; TOP: 104px"
                        runat="server" Height="27px" Width="143px" RepeatDirection="Horizontal" AutoPostBack="True">
                        <asp:ListItem Value="TPS" Selected="True">TPS</asp:ListItem>
                        <asp:ListItem Value="LICI">LICI</asp:ListItem>
                  </asp:radiobuttonlist><asp:label id="Label4" style="Z-INDEX: 109; LEFT: 122px; POSITION: absolute; TOP: 109px" runat="server"
                        Height="21px" Width="70px">Processing:</asp:label></form>
      </body>
</HTML>




C# Page load.

      private void Page_Load(object sender, System.EventArgs e)
      {
         m_UserName = CurrentUsername;
         DefaultButton.Set(this.Page, txtDocumentNum, btnAdd);

         if (this.optSystem.SelectedValue == "TPS")
         {
            m_ConnectionString = TPSConnectionString;
            sb.Append("select distinct doctype from drm.m_doctype order by doctype");
         }
         else
         {
            m_ConnectionString = LICIConnectionString;
            sb.Append("select distinct doctype from licidrm.m_doctype order by doctype");
         }

         using (OracleConnection cn = new OracleConnection(this.m_ConnectionString))
         {
            adapter1.SelectCommand = new OracleCommand(sb.ToString(), cn);
            adapter1.Fill(ds, "doctypes");
         }
         this.cboDoctypes.DataSource = ds.Tables["doctypes"];
         this.cboDoctypes.SelectedIndex = 0;
         this.cboDoctypes.DataTextField = ds.Tables["doctypes"].Columns[0].ToString();
         this.cboDoctypes.DataBind();
         sb.Remove(0,sb.Length);

         sb.Append("select tfc.dream_doctype ");
         sb.Append(", tfc.DREAM_DOCNUM ");
         sb.Append(", decode(tfc.ACTION_IND,'F', 'Failed','O','Outstanding') action_ind");
         sb.Append(", tfc.REQUEST_DATE ");
         sb.Append("from drmext.t_feedback_control tfc ");
         sb.Append("where tfc.action_ind <> 'C' ");
         sb.Append("order by tfc.request_date desc");
   
         using (OracleConnection cn = new OracleConnection(this.m_ConnectionString))
         {
            adapter.SelectCommand = new OracleCommand(sb.ToString(), cn);
            adapter.Fill(ds, "requests");
         }
         dgControlItems.DataSource = ds.Tables["requests"];
         dgControlItems.DataBind();
      }

i created a test aspx page and added ur radiobutton .. and even added the enable viewstate = false (basically radio button, checkbox, textbox and really not affected by the viewstate=false) for the page and control .. but stil it retained the value when submitted ... i did a response.write in my load to check the selected value and it shows the right value
>>When I select the second button and add a record
what do u mean by "add a record" .... the autopostback for the radiobutton is set to true . .so tha pge gets submitted whenever the a selection is made by the user ...
ok ... what is ur problem exactly as u mentioned above
>>the startup button is re-selected and the original datalist displayed.
if it is that ur datalist is getting defaulted back to its original state then ... it is because ur datalist's enableviewstate is set to false .. and also the code to load it is in the page_onload which will fired all the time ..

Also u might want to move the code to populate the datalist from the load event to the selectedindexChanged event of the radiobutton .. and in the load event check for the condition if not ispostback and populate the datalist the FIRST time when the page gets loaded based on the default selected radiobutton
There's an 'Add' button on the page.
Basically the user selects a document type from the combobox, enters a document number, hits 'Add' and it goes off and updates a database table.
The database it updates depends on the radio button setting.
Now, if I select the second button, the page reloads and shows the document types for that database  - fine.
Select an enrty from the combobox, enter a number and click 'Add' and when the page reloads, the 1st radio button is selected (of course, showing the correct data for that selection).

I check the value of the radiobutton on page_load to determine what data gets put into the combobox. Because I do that, I dsabled viewstate on the combo to save room.
could u please post th code for the "add" part ...
This is the whole thing - it's not big.


using System;
using System.Collections;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.OracleClient;
using System.Security.Principal;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Text;
using ASP_Utils;

namespace Dream_Feedback_Control
{
   /// <summary>
   /// Summary description for WebForm1.
   /// </summary>
   public class WebForm1 : System.Web.UI.Page
   {
      protected System.Web.UI.WebControls.Label Label2;
      protected System.Web.UI.WebControls.Label Label3;
      protected System.Web.UI.WebControls.Button btnAdd;
      protected System.Web.UI.WebControls.Label Label1;
      protected System.Web.UI.WebControls.DropDownList cboDoctypes;
      protected System.Web.UI.WebControls.RadioButtonList optSystem;
      protected System.Web.UI.WebControls.Label Label4;
      protected System.Web.UI.WebControls.TextBox txtDocumentNum;
      protected System.Web.UI.WebControls.DataGrid dgControlItems;

      OracleDataAdapter adapter = new OracleDataAdapter();
      OracleDataAdapter adapter1 = new OracleDataAdapter();
      DataSet   ds = new DataSet();
      string       m_ConnectionString;
      string       m_UserName;
      StringBuilder sb = new StringBuilder();

      private void Page_Load(object sender, System.EventArgs e)
      {
         m_UserName = CurrentUsername;
         DefaultButton.Set(this.Page, txtDocumentNum, btnAdd);

         if (this.optSystem.SelectedValue == "TPS")
         {
            m_ConnectionString = TPSConnectionString;
            sb.Append("select distinct doctype from drm.m_doctype order by doctype");
         }
         else
         {
            m_ConnectionString = LICIConnectionString;
            sb.Append("select distinct doctype from licidrm.m_doctype order by doctype");
         }

         using (OracleConnection cn = new OracleConnection(this.m_ConnectionString))
         {
            adapter1.SelectCommand = new OracleCommand(sb.ToString(), cn);
            adapter1.Fill(ds, "doctypes");
         }
         this.cboDoctypes.DataSource = ds.Tables["doctypes"];
         this.cboDoctypes.SelectedIndex = 0;
         this.cboDoctypes.DataTextField = ds.Tables["doctypes"].Columns[0].ToString();
         this.cboDoctypes.DataBind();
         sb.Remove(0,sb.Length);

         sb.Append("select tfc.dream_doctype ");
         sb.Append(", tfc.DREAM_DOCNUM ");
         sb.Append(", decode(tfc.ACTION_IND,'F', 'Failed','O','Outstanding') action_ind");
         sb.Append(", tfc.REQUEST_DATE ");
         sb.Append("from drmext.t_feedback_control tfc ");
         sb.Append("where tfc.action_ind <> 'C' ");
         sb.Append("order by tfc.request_date desc");
   
         using (OracleConnection cn = new OracleConnection(this.m_ConnectionString))
         {
            adapter.SelectCommand = new OracleCommand(sb.ToString(), cn);
            adapter.Fill(ds, "requests");
         }
         dgControlItems.DataSource = ds.Tables["requests"];
         dgControlItems.DataBind();
      }


      #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);
      }
            
      /// <summary>
      /// Required method for Designer support - do not modify
      /// the contents of this method with the code editor.
      /// </summary>
      private void InitializeComponent()
      {    
         this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
         this.dgControlItems.DeleteCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgControlItems_DeleteCommand);
         this.Load += new System.EventHandler(this.Page_Load);

      }
      #endregion


      private void btnAdd_Click(object sender, System.EventArgs e)
      {
         if(this.txtDocumentNum.Text.Length == 0)
         {
            MessageBox.Show("Please enter a document number");
            return;
         }

         foreach ( char chr in txtDocumentNum.Text.ToCharArray())
         {
            //Check whether the value is numeric
            if(!IsNumeric(chr))
            {
               MessageBox.Show("Document number must be numeric ");
               return;
            }
         }
         
         StringBuilder sb = new StringBuilder();
      
         sb.Append("INSERT INTO drmext.T_FEEDBACK_CONTROL  ");
         sb.Append("( DREAM_DOCTYPE ");
         sb.Append(", DREAM_DOCNUM ");
         sb.Append(", ACTION_IND ");
         sb.Append(", USERNAME");
         sb.Append(", REQUEST_DATE )  ");
         sb.Append("VALUES (  ");
         sb.Append("'" + this.cboDoctypes.SelectedValue + "'");
         sb.Append("," + this.txtDocumentNum.Text + "");
         sb.Append(", 'O' ");
         sb.Append(",'" + m_UserName + "'");
         sb.Append(",  sysdate ");
         sb.Append(") ");

         using (OracleConnection cn = new OracleConnection(this.m_ConnectionString))
         {
            cn.Open();

            using (OracleCommand c = new OracleCommand( sb.ToString(),cn))
            {
               try
               {
                  c.ExecuteNonQuery();
                  this.txtDocumentNum.Text = "";
               }
               catch (Exception e1)
               {
                  if (e1.Message.StartsWith("ORA-00001"))
                  {
                     MessageBox.Show("This item already exists");
                  }
                  else
                  {
                     MessageBox.Show(e1.Message);
                  }
               }
               cn.Close();
            }
         }
         Response.Redirect("WebForm1.aspx");
      }

      private void dgControlItems_DeleteCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
      {
         StringBuilder sb = new StringBuilder();
         sb.Append("update drmext.T_FEEDBACK_CONTROL " );
         sb.Append("set action_ind = 'C' ");
         sb.Append(", USERNAME = '" + m_UserName + "'");
         sb.Append(", request_date = sysdate ");
         sb.Append("where DREAM_DOCTYPE  = '" + e.Item.Cells[1].Text + "' ");
         sb.Append("and DREAM_DOCNUM = " + e.Item.Cells[2].Text + " ");

         using (OracleConnection cn = new OracleConnection(this.m_ConnectionString))
         {
            cn.Open();

            using (OracleCommand c = new OracleCommand( sb.ToString(),cn))
            {
               try
               {
                  c.ExecuteNonQuery();
               }
               catch (Exception e1)
               {
                  MessageBox.Show(e1.Message);
               }
               cn.Close();
            }
         }
         Response.Redirect("WebForm1.aspx");
      }

      private string TPSConnectionString
      {
         get
         {
            return ConfigurationSettings.AppSettings["TPSConnectionString"].ToString();                        
         }
      }
      private string LICIConnectionString
      {
         get
         {
            return ConfigurationSettings.AppSettings["LICIConnectionString"].ToString();                        
         }
      }
      protected string CurrentUsername
      {
         get
         {
            System.Security.Principal.WindowsImpersonationContext impersonationContext;
            impersonationContext = ((System.Security.Principal.WindowsIdentity)User.Identity).Impersonate();
            WindowsIdentity winIdent = WindowsIdentity.GetCurrent();
            string windowsLogin = winIdent.Name;
            int slashpoint = windowsLogin.IndexOf(@"\");
            impersonationContext.Undo();
            return windowsLogin.Substring(slashpoint+1,windowsLogin.Length-(slashpoint+1));
         }
      }  
      protected bool IsNumeric(int Val)
      {
         return ((Val>=48 && Val<=57));
      }
   }
}



// common utils I've picked up.


using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Text;

namespace ASP_Utils
{
   public class DefaultButton
   {
      private DefaultButton()
      { }

      /// <summary>
      /// Sets the Button you want to submit when the Enter key is pressed within a TextBox.
      /// </summary>
      /// <param name="thisPage">The container page of the TextBox and Button</param>
      /// <param name="textControl">The TextBox to monitor for the Enter key</param>
      /// <param name="defaultButton">The Button you want to click when the Enter key is pressed</param>
      /// Usage
      /// In page_load;
      ///                   DefaultButton.Set(this.Page, TextBox1, Button1);
      ///         DefaultButton.Set(this.Page, TextBox2, ImageButton1);
      ///         DefaultButton.Set(this.Page, TextBox3, Button3);

      public static void Set(Page thisPage, TextBox textControl, WebControl defaultButton)
      {
         // Sets default buttons.
         // Originally created by Janus Kamp Hansen - http://www.kamp-hansen.dk
         // Extended by Darrell Norton - http://dotnetjunkies.com/weblog/darrell.norton/ 
         // Available at http://www.gotdotnet.com/Community/Workspaces/Workspace.aspx?id=a3b93959-9b2e-428a-99d9-276f0620589d
         string theImageScript = @"
                  <SCRIPT language=""javascript"">
                  <!--
                  function fnTrapKD(btnID, event){
                  btn = findObj(btnID);
                  if (document.all){
                  if (event.keyCode == 13){
                     event.returnValue=false;
                     event.cancel = true;
                     btn.click();
                  }
                  }
                  else if (document.getElementById){
                  if (event.which == 13){
                     event.returnValue=false;
                     event.cancel = true;
                     btn.focus();
                     btn.click();
                  }
                  }
                  else if(document.layers){
                  if(event.which == 13){
                     event.returnValue=false;
                     event.cancel = true;
                     btn.focus();
                     btn.click();
                  }
                  }
                  }

                  function findObj(n, d) {
                        var p,i,x;  
                        if(!d)
                              d=document;
                        if((p=n.indexOf(""?""))>0 && parent.frames.length) {
                              d=parent.frames[n.substring(p+1)].document;
                              n=n.substring(0,p);
                        }
                        if(!(x=d[n])&&d.all)
                              x=d.all[n];
                        for (i=0;!x&&i<d.forms.length;i++)
                              x=d.forms[i][n];
                        for(i=0;!x&&d.layers&&i<d.layers.length;i++)
                              x=findObj(n,d.layers[i].document);
                        if(!x && d.getElementById)
                              x=d.getElementById(n);
                        return x;
                  }
                  // -->
                  </SCRIPT>";

         textControl.Attributes.Add("onkeydown", "fnTrapKD('" + defaultButton.ClientID + "',event)");
         thisPage.RegisterStartupScript("ForceDefaultToScriptImage", theImageScript);
      }

   }

   /// <summary>
      /// Provides MessageBox functionality for web pages
      /// For validation, several .Shows can be queued. They will displayed in the same alert.
      /// e.g.  MessageBox.Show("Product id must be provided");
      ///       Messagebox.Show("Amount must be > zero");  etc.
      /// </summary>
   public class MessageBox
   {
      //
      // Courtesy Lee Gunn
      //
      private static Hashtable m_executingPages = new Hashtable();

      private MessageBox(){}

      public static void Show( string sMessage )
      {
         // If this is the first time a page has called this method then
         if( !m_executingPages.Contains( HttpContext.Current.Handler ) )
         {
            // Attempt to cast HttpHandler as a Page.
            Page executingPage = HttpContext.Current.Handler as Page;

            if( executingPage != null )
            {
               // Create a Queue to hold one or more messages.
               Queue messageQueue = new Queue();

               // Add our message to the Queue
               messageQueue.Enqueue( sMessage );

               // Add our message queue to the hash table. Use our page reference
               // (IHttpHandler) as the key.
               m_executingPages.Add( HttpContext.Current.Handler, messageQueue );

               // Wire up Unload event so that we can inject
               // some JavaScript for the alerts.
               executingPage.Unload += new EventHandler( ExecutingPage_Unload );
            }  
         }
         else
         {
            // If were here then the method has already been
            // called from the executing Page.
            // We have already created a message queue and stored a
            // reference to it in our hastable.
            Queue queue = (Queue) m_executingPages[ HttpContext.Current.Handler ];

            // Add our message to the Queue
            queue.Enqueue( sMessage );
         }
      }


      // Our page has finished rendering so let's output the
      // JavaScript to produce the alerts
      private static void ExecutingPage_Unload(object sender, EventArgs e)
      {
         // Get our message queue from the hashtable
         Queue queue = (Queue) m_executingPages[ HttpContext.Current.Handler ];

         if( queue != null )
         {
            StringBuilder sb = new StringBuilder();

            // How many messages have been registered?
            int iMsgCount = queue.Count;

            // Use StringBuilder to build up our client side JavaScript.
            sb.Append( "<script language='javascript'>" );

            // Loop round registered messages
            string sMsg;
            while( iMsgCount-- > 0 )
            {
               sMsg = (string) queue.Dequeue();
               sMsg = sMsg.Replace( "\n", "\\n" );
               sMsg = sMsg.Replace( "\"", "'" );
               sb.Append( @"alert( """ + sMsg + @""" );" );
            }

            // Close our JS
            sb.Append( @"</script>" );

            // We're done, so remove our page reference from the hashtable
            m_executingPages.Remove( HttpContext.Current.Handler );

            // Write the JavaScript to the end of the response stream.
            HttpContext.Current.Response.Write( sb.ToString() );
         }
      }

   }
}

i am not familliar with C# .. have always coded in VB.net ... what does
DefaultButton.Set(this.Page, txtDocumentNum, btnAdd);
do? does it set the add button as default?
yes, that's right.
sorry ... saw ur code after submitting the question .. let me check this out ... will get back if i have some answer ...
ASKER CERTIFIED SOLUTION
Avatar of Rejojohny
Rejojohny
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes, you're right.
I put that in there on my team leader's advice, because without it the form didn't postback immediately.
So I would hit add and nothing would change, add another item and the previous item turned up!

That redirect solved it.

Solve one problem , create another B-(
many thanls.

Graham
thx for the points ..
>>without it the form didn't postback immediately.
what do u mean .. i do not use a redirect statement to post to the same page and it works fine for me . no delays ...

Also just keep a note that the next time u post a question .. it would be better to mention exactly what u r trying to do ..  i mean instead of others questioning ur each step .. it would be better to post the exact scenario .. if u had mentioned about the "add" button before and the case that it is when u click "add" that the radio gets defaulted to its original state , i might ask for the code immediately ... anway .. glad to be of help .. but had to post and read a lot of comments for 125 points ;-)
Sorry, thought I had described the scenario enough (being too close, I guess).

I have a delete butoon in the grid, which posts back immediately - no problem.
It's just that add button.

Another 125 points for you if you can spot this one as well.
that is a tough one to come up with .. wil lhave to debug the code and check where the time is taken .. u could try doing that by adding breakpoints .. basically ur code doesn;t have anything specific which should delay the page execution process .. unless ofcourse ur network speed to the database ia problme or u have a trigger on ur table for "insert" or the table is very huge and indexing is taking the time .. but then these issues would not have got solved by adding a response.redirect statement ...
I've put breakpoints in and there's no problem.
The code goes straight through and the page is redisplayed.
The table doesn't even get updated at that point. I 've gone and looked at the table.
But as soon as I hit the 'add' button again (and it comes up with the alert to say there is no document number), the grid is magically refreshed behind it(the alert) with the previously added record.
Weird or what ?
it works exactly as it is supposed to .. try to understand how the page processes it self .. when a page is requested .. it starts tih its load event .. then loads the page and executes any client-script (if any) ... when the add button is clicked, again the first thing that happens is the load event .. and ur grid gets bound again .. then the code for the click of the "add" button is executed and the data gets inserted into the database .. then the whole page is send to the browser .. now u press tha add button again .. the load event happens again .. the grid gets refrehsed .. the add button validates the textbox and goes into exception .. the way u have handled exception is that it calls a class which generates the javascript "alert" statement .. remember the code is still executing and so the alert is not shown now as the code been executed is still at the server .. now the page gets rendered onto the browser .. now the alert statement gets fired and u see the messagebox and as the grid was also refreshed during load .. it gets refreshed on the browser too ... got it???
Ok, I see.
What needs to happen is that the grid gets refreshed when the whole page is sent to the browser (before I hit the add button again).
How do I make that happen?


u could disable the button (by default) and enable it the load event (client side script - body's onload) of the page ... so basically what u r ensuring is that the page gets loaded completely before the user has access to the "add" button ...
Maybe I haven't made myself clear(again!).
The page gets redisplayed and I can select another document type from the combo, enter a document number and click the add button.
It will then go off as though it's adding a new record, then suddenly the previous record will appear(but not the new one).
So it all seems to be working OK.
It's just that the page is not refreshed once the add button has finished adding the new record.
Almost like it's out of step.
that is what i was trying to say .. if u disable the button and only enable it on "load" then u will not be able to add the second record and click on "add" until the page gets loaded completely ...

anyway .. i do not think tat exactly is ur problem here .. what exactly do u mean by the previous record will appear . .how do u determine that .. looking at the grid??
Yes, I add a record and it should appear in the grid.
But, it doesn't until the add button is hit again.
I can see what it's doing now - just been debugging it.
When I hit add, it does a page load, then processes the button, but doesn't refresh the page !!!

I think I'm getting the hang of this now.
I 'll work aout a way round this myself.
Thanks for your help - points here
https://www.experts-exchange.com/questions/21177005/points-for-rejojohnny.html

Graham
This session seems like chatting :-)

ok . as i said before ... the load event gets fired first whenever a page gets loaded .. so what is happening in ur case is the grid gets refreshed (in load and the new record is not yet added) .. then the add click event gets fired .. and the new record gets added ..

normally how i would code is this way
i have a function called refreshgrid (to get new values and bind), refreshList( to get new values based on teh radio button selection and bind)

load event ...
if not ispostback then ''' check page is oepned fo the first time
   call refreshlist
  call refreshgrid
end if

add click event
.. add the new record
   call refreshlist
  call refreshgrid
 
delete event
..delete the record
   call refreshlist
  call refreshgrid


and i would enable the viewstate of these controls so that i do not have to fetch the values from the database even when i face a error in any of the events .. then what i would do is ...

'add click event
... add the record
if successful then
   call refreshlist
  call refreshgrid
end if


hope u got it now ...so basically nothing to do with the page not geting refreshed in time .. it is basically the code was not getting the valules at the correct time .. the response.redirect statement earlier used to fetch the load event of the page
again after the add click or delete code was completed .. so basically in that case the load event was getting called TWICE .. and it was the second time that the grid was getting refreshed with the new value ...

hope that now i have solved that problem too .. i will get more than the promised poirnts .. have really spend a lot of time on this single query .. have to get back to work now :-)
Thanks - That's the way I'm refactoring it at the moment.
Interestingly enough, the delete button in the grid DOES refresh the grid at the time it does it.
That's what threw me off what was happening ...and when.

So an extra 125 points isn't enough ?
If you go and post a comment at the new question, I'll up them some more.
You drive a hard bargain B-)
thx for the points .. ya i do drive a hard bargain ;-) But really, glad to be of help .. hope it helps u out when u write the code the next aspx page .. the sequence is a bit tricky here as u would always expect the corresponding event to be called the first and not the page_load .. it becomes more confusing for the first few pages if u have exp. in coding using VB or the classic ASP ..

BTW the delete too should have worked in a similar fashion ... give me some more points and i will look into it ;-) on a serious note, sorry, no idea y it should behave differenetly .. r u sure it gets refreshed immediately without the response.redirect stement ... remember u have that statement at the end of that event too ...
Damn - you're right.
Forgot I had that there as well.
Thanks again - you earned the points.

:-) .. sh**, i should have asked for points before providing u with the solution :-)

BTW .. I drove a hard bargain before on the points because I am about to get a Master level certificate from EE for the ASP topic area .. just a matter of around 1500 more points .. so each and every point matters now ... otherwise i wouldn't have really cared .. i enjoy doing this ..
Hope you make it - good luck.