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
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
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 ?
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 ...
ASKER
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.
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\F ramework\v 1.1.4322\C ONFIG ..
>>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 ...
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 ...
ASKER
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_C ontrol.Web Form1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML xmlns:v="urn:schemas-micro soft-com:v ml">
<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_defaultClientScri pt">
<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:dr opdownlist id="cboDoctypes" style="Z-INDEX: 102; LEFT: 226px; POSITION: absolute; TOP: 153px"
runat="server" Height="24px" Width="89px" EnableViewState="False"></ asp:dropdo wnlist><as p:textbox id="txtDocumentNum" style="Z-INDEX: 103; LEFT: 475px; POSITION: absolute; TOP: 151px"
runat="server" Height="24" Width="87px" MaxLength="10" EnableViewState="False"></ asp:textbo x><asp:lab el id="Label2" style="Z-INDEX: 104; LEFT: 123px; POSITION: absolute; TOP: 156px" runat="server"
Height="10px" Width="103px">Document Type:</asp:label><asp:labe l id="Label3" style="Z-INDEX: 105; LEFT: 354px; POSITION: absolute; TOP: 156px" runat="server"
Height="15px" Width="121px">Document Number:</asp:label><asp:bu tton 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:da tagrid 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"></Alte rnatingIte mStyle>
<HeaderStyle Font-Bold="True"></HeaderS tyle>
<Columns>
<asp:ButtonColumn Text="Remove" CommandName="Delete">
<ItemStyle ForeColor="#FF3300"></Item Style>
</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: BoundColum n>
<asp:BoundColumn DataField="request_date" ReadOnly="True" HeaderText="Request Date"></asp:BoundColumn>
</Columns>
</asp:datagrid><asp:radiob uttonlist id="optSystem" style="Z-INDEX: 108; LEFT: 206px; POSITION: absolute; TOP: 104px"
runat="server" Height="27px" Width="143px" RepeatDirection="Horizonta l" AutoPostBack="True">
<asp:ListItem Value="TPS" Selected="True">TPS</asp:L istItem>
<asp:ListItem Value="LICI">LICI</asp:Lis tItem>
</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.Pag e, txtDocumentNum, btnAdd);
if (this.optSystem.SelectedVa lue == "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_Co nnectionSt ring))
{
adapter1.SelectCommand = new OracleCommand(sb.ToString( ), cn);
adapter1.Fill(ds, "doctypes");
}
this.cboDoctypes.DataSourc e = ds.Tables["doctypes"];
this.cboDoctypes.SelectedI ndex = 0;
this.cboDoctypes.DataTextF ield = ds.Tables["doctypes"].Colu mns[0].ToS tring();
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_Co nnectionSt ring))
{
adapter.SelectCommand = new OracleCommand(sb.ToString( ), cn);
adapter.Fill(ds, "requests");
}
dgControlItems.DataSource = ds.Tables["requests"];
dgControlItems.DataBind();
}
<%@ Page language="c#" Codebehind="WebForm1.aspx.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML xmlns:v="urn:schemas-micro
<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_defaultClientScri
<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:dr
runat="server" Height="24px" Width="89px" EnableViewState="False"></
runat="server" Height="24" Width="87px" MaxLength="10" EnableViewState="False"></
Height="10px" Width="103px">Document Type:</asp:label><asp:labe
Height="15px" Width="121px">Document Number:</asp:label><asp:bu
Height="27px" Width="97px" BackColor="PaleGreen" Text="Add Item"></asp:button><asp:da
runat="server" Height="122px" Width="697px" AutoGenerateColumns="False
<AlternatingItemStyle BackColor="#E0E0E0"></Alte
<HeaderStyle Font-Bold="True"></HeaderS
<Columns>
<asp:ButtonColumn Text="Remove" CommandName="Delete">
<ItemStyle ForeColor="#FF3300"></Item
</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:
<asp:BoundColumn DataField="request_date" ReadOnly="True" HeaderText="Request Date"></asp:BoundColumn>
</Columns>
</asp:datagrid><asp:radiob
runat="server" Height="27px" Width="143px" RepeatDirection="Horizonta
<asp:ListItem Value="TPS" Selected="True">TPS</asp:L
<asp:ListItem Value="LICI">LICI</asp:Lis
</asp:radiobuttonlist><asp
Height="21px" Width="70px">Processing:</
</body>
</HTML>
C# Page load.
private void Page_Load(object sender, System.EventArgs e)
{
m_UserName = CurrentUsername;
DefaultButton.Set(this.Pag
if (this.optSystem.SelectedVa
{
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_Co
{
adapter1.SelectCommand = new OracleCommand(sb.ToString(
adapter1.Fill(ds, "doctypes");
}
this.cboDoctypes.DataSourc
this.cboDoctypes.SelectedI
this.cboDoctypes.DataTextF
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',
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_Co
{
adapter.SelectCommand = new OracleCommand(sb.ToString(
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 ...
>>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
>>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
ASKER
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.
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 ...
ASKER
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. DropDownLi st cboDoctypes;
protected System.Web.UI.WebControls. RadioButto nList 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.Pag e, txtDocumentNum, btnAdd);
if (this.optSystem.SelectedVa lue == "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_Co nnectionSt ring))
{
adapter1.SelectCommand = new OracleCommand(sb.ToString( ), cn);
adapter1.Fill(ds, "doctypes");
}
this.cboDoctypes.DataSourc e = ds.Tables["doctypes"];
this.cboDoctypes.SelectedI ndex = 0;
this.cboDoctypes.DataTextF ield = ds.Tables["doctypes"].Colu mns[0].ToS tring();
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_Co nnectionSt ring))
{
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.b tnAdd_Clic k);
this.dgControlItems.Delete Command += new System.Web.UI.WebControls. DataGridCo mmandEvent Handler(th is.dgContr olItems_De leteComman d);
this.Load += new System.EventHandler(this.P age_Load);
}
#endregion
private void btnAdd_Click(object sender, System.EventArgs e)
{
if(this.txtDocumentNum.Tex t.Length == 0)
{
MessageBox.Show("Please enter a document number");
return;
}
foreach ( char chr in txtDocumentNum.Text.ToChar Array())
{
//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.SelectedV alue + "'");
sb.Append("," + this.txtDocumentNum.Text + "");
sb.Append(", 'O' ");
sb.Append(",'" + m_UserName + "'");
sb.Append(", sysdate ");
sb.Append(") ");
using (OracleConnection cn = new OracleConnection(this.m_Co nnectionSt ring))
{
cn.Open();
using (OracleCommand c = new OracleCommand( sb.ToString(),cn))
{
try
{
c.ExecuteNonQuery();
this.txtDocumentNum.Text = "";
}
catch (Exception e1)
{
if (e1.Message.StartsWith("OR A-00001"))
{
MessageBox.Show("This item already exists");
}
else
{
MessageBox.Show(e1.Message );
}
}
cn.Close();
}
}
Response.Redirect("WebForm 1.aspx");
}
private void dgControlItems_DeleteComma nd(object source, System.Web.UI.WebControls. DataGridCo mmandEvent Args 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_Co nnectionSt ring))
{
cn.Open();
using (OracleCommand c = new OracleCommand( sb.ToString(),cn))
{
try
{
c.ExecuteNonQuery();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message );
}
cn.Close();
}
}
Response.Redirect("WebForm 1.aspx");
}
private string TPSConnectionString
{
get
{
return ConfigurationSettings.AppS ettings["T PSConnecti onString"] .ToString( );
}
}
private string LICIConnectionString
{
get
{
return ConfigurationSettings.AppS ettings["L ICIConnect ionString" ].ToString ();
}
}
protected string CurrentUsername
{
get
{
System.Security.Principal. WindowsImp ersonation Context impersonationContext;
impersonationContext = ((System.Security.Principa l.WindowsI dentity)Us er.Identit y).Imperso nate();
WindowsIdentity winIdent = WindowsIdentity.GetCurrent ();
string windowsLogin = winIdent.Name;
int slashpoint = windowsLogin.IndexOf(@"\") ;
impersonationContext.Undo( );
return windowsLogin.Substring(sla shpoint+1, windowsLog in.Length- (slashpoin t+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.Pag e, TextBox1, Button1);
/// DefaultButton.Set(this.Pag e, TextBox2, ImageButton1);
/// DefaultButton.Set(this.Pag e, 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.substrin g(p+1)].do cument;
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.len gth;i++)
x=findObj(n,d.layers[i].do cument);
if(!x && d.getElementById)
x=d.getElementById(n);
return x;
}
// -->
</SCRIPT>";
textControl.Attributes.Add ("onkeydow n", "fnTrapKD('" + defaultButton.ClientID + "',event)");
thisPage.RegisterStartupSc ript("Forc eDefaultTo ScriptImag e", 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.Handle r ) )
{
// Attempt to cast HttpHandler as a Page.
Page executingPage = HttpContext.Current.Handle r 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.Handle r, 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.Handle r ];
// 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(objec t sender, EventArgs e)
{
// Get our message queue from the hashtable
Queue queue = (Queue) m_executingPages[ HttpContext.Current.Handle r ];
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.Handle r );
// Write the JavaScript to the end of the response stream.
HttpContext.Current.Respon se.Write( sb.ToString() );
}
}
}
}
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.
protected System.Web.UI.WebControls.
protected System.Web.UI.WebControls.
protected System.Web.UI.WebControls.
protected System.Web.UI.WebControls.
protected System.Web.UI.WebControls.
protected System.Web.UI.WebControls.
protected System.Web.UI.WebControls.
protected System.Web.UI.WebControls.
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.Pag
if (this.optSystem.SelectedVa
{
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_Co
{
adapter1.SelectCommand = new OracleCommand(sb.ToString(
adapter1.Fill(ds, "doctypes");
}
this.cboDoctypes.DataSourc
this.cboDoctypes.SelectedI
this.cboDoctypes.DataTextF
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',
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_Co
{
adapter.SelectCommand = new OracleCommand(sb.ToString(
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.b
this.dgControlItems.Delete
this.Load += new System.EventHandler(this.P
}
#endregion
private void btnAdd_Click(object sender, System.EventArgs e)
{
if(this.txtDocumentNum.Tex
{
MessageBox.Show("Please enter a document number");
return;
}
foreach ( char chr in txtDocumentNum.Text.ToChar
{
//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.SelectedV
sb.Append("," + this.txtDocumentNum.Text + "");
sb.Append(", 'O' ");
sb.Append(",'" + m_UserName + "'");
sb.Append(", sysdate ");
sb.Append(") ");
using (OracleConnection cn = new OracleConnection(this.m_Co
{
cn.Open();
using (OracleCommand c = new OracleCommand( sb.ToString(),cn))
{
try
{
c.ExecuteNonQuery();
this.txtDocumentNum.Text = "";
}
catch (Exception e1)
{
if (e1.Message.StartsWith("OR
{
MessageBox.Show("This item already exists");
}
else
{
MessageBox.Show(e1.Message
}
}
cn.Close();
}
}
Response.Redirect("WebForm
}
private void dgControlItems_DeleteComma
{
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_Co
{
cn.Open();
using (OracleCommand c = new OracleCommand( sb.ToString(),cn))
{
try
{
c.ExecuteNonQuery();
}
catch (Exception e1)
{
MessageBox.Show(e1.Message
}
cn.Close();
}
}
Response.Redirect("WebForm
}
private string TPSConnectionString
{
get
{
return ConfigurationSettings.AppS
}
}
private string LICIConnectionString
{
get
{
return ConfigurationSettings.AppS
}
}
protected string CurrentUsername
{
get
{
System.Security.Principal.
impersonationContext = ((System.Security.Principa
WindowsIdentity winIdent = WindowsIdentity.GetCurrent
string windowsLogin = winIdent.Name;
int slashpoint = windowsLogin.IndexOf(@"\")
impersonationContext.Undo(
return windowsLogin.Substring(sla
}
}
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.Pag
/// DefaultButton.Set(this.Pag
/// DefaultButton.Set(this.Pag
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.substrin
n=n.substring(0,p);
}
if(!(x=d[n])&&d.all)
x=d.all[n];
for (i=0;!x&&i<d.forms.length;
x=d.forms[i][n];
for(i=0;!x&&d.layers&&i<d.
x=findObj(n,d.layers[i].do
if(!x && d.getElementById)
x=d.getElementById(n);
return x;
}
// -->
</SCRIPT>";
textControl.Attributes.Add
thisPage.RegisterStartupSc
}
}
/// <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
{
// Attempt to cast HttpHandler as a Page.
Page executingPage = HttpContext.Current.Handle
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.Handle
// 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.Handle
// 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(objec
{
// Get our message queue from the hashtable
Queue queue = (Queue) m_executingPages[ HttpContext.Current.Handle
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.Handle
// Write the JavaScript to the end of the response stream.
HttpContext.Current.Respon
}
}
}
}
i am not familliar with C# .. have always coded in VB.net ... what does
DefaultButton.Set(this.Pag e, txtDocumentNum, btnAdd);
do? does it set the add button as default?
DefaultButton.Set(this.Pag
do? does it set the add button as default?
ASKER
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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-(
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-(
ASKER
many thanls.
Graham
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 ;-)
>>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 ;-)
ASKER
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.
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 ...
ASKER
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 ?
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???
ASKER
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?
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 ...
ASKER
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.
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??
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??
ASKER
Yes, I add a record and it should appear in the grid.
But, it doesn't until the add button is hit again.
But, it doesn't until the add button is hit again.
ASKER
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
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 :-)
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 :-)
ASKER
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-)
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 ...
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 ...
ASKER
Damn - you're right.
Forgot I had that there as well.
Thanks again - you earned the points.
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 ..
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 ..
ASKER
Hope you make it - good luck.
<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