I am adding some additional code to a C# 2010 web form application that I would like suggestions on how to accomplish the following:
1. I just created an additonal web form page to an existing application so the user can enter more information. I basically want the user to hit the 'back' button so they can return to the original web page and correct the values for up to 4 specific fields.
There are two additional fields that the user is not allowed to change.
2. To point the user to the previous page, I do the command, "Response.Redirect("~/Att.aspx"); This works,
3. I want to be able to load all the information the user has entered already when the user returns to this web page. When the user returns to this webpage, the data has already been stored in two tables in the database.
4. Thus I am looking for your suggestion on how to accomplish this goal. I am thinking of the following options:
a. returning the user to the orginal web page in the state it was when they hit the 'next' button to go to the previous webpage. However I do not know how to proceed with this method.
b. Obtain the values from the database, or
c. use session variables. Thus can you tell me what you think the best method would be and examples of code of how you would accomplish this goal?
I would start by trying it out as is first, have you done that? Also I like to use the record key in the query string and the do a if onm the query string using the key to load all the data from the database. I am on my phone so I can't post any code but
I will try to give you idea later. Something like. http://www.myfirstpage.aspx?id=1 So on pageload you ckeck for id and then call you DAL layer and fetch the data and fill the form before displaying it. You could also use session objects and load the form
back up, I would tell you ppl will start a long winded debate over something like this, but I get a feeling this is not some huge and or mission critical web app, so technically whatever feels good for you is fine.
I want to mention the following in response to your answer:
1. Passing a query string value back to the first page is not a good idea since there is too much information to pass that needs to be encrypted.
2. Right now in the application, I am passing session variables from the first web page to the second web page. I am thinking it would be a good idea to pass session variables from the second web page to the first web page. Can I somehow reuse the session
varirables I setup on the second web page? If not, would I need to create some new session variables on the first web page?
3. I do want to mention all the data I need is already stored in the database.
4. I have tried to load some of the data to the intital web page but I had a few problems. I have the following 6 items that I need to populate data with:
1. The name of the company. This feature needs to be grayed since the user will not be able to change it. (Note: this textbox was originally populated using a type a head feature.
2. The subcompany numbers will be grayed out also since the user can not change this. (Note: this is a initially a checkbox list control where the user selects the subcompanies.)
3. There are two dropdown list controls that had the initial value set to 'N' for no. These two options the user can change when they hit the 'back' button. I want to be able to reload 'Y' or 'N', whatever is in the database.
4. There also is a create date that is split into 2 columns. One column is for month and another column is for year. The user can change this date also once they hit the back button. These two fields initially are loaded with dropdown list values that are
loaded in the database.
Thus to start with, I would need to figure out how to reload the first page with the values from the database. I then would need to make the dropdown features work again.
Passing the session variaables back to the first page would be needed since these values are the keys to the database tables.
The user navigates to Page 2 and then Clicks the Back Button to return to Page1.ASPX
You can now retreive the Session Values and use them to reset your form to how it was before
protectedvoid Page_Load(object sender, EventArgs e)
{ if (!IsPostBack) { // Reset the DropDownlist to the Selected Index mydropdownlist1.selectedindex = Convert.ToInt32(Session["DDL_MyDropDownList1Index"]); mydropdownlist2.selectedindex = Convert.ToInt32(Session["DDL_MyDropDownList2Index"]);
// call a method to reload the form from the DataBase loadtheform(); }
}
protectedvoid loadtheform()
{
// Use the Session Variables to read the Database and reload the Textboxes and all other
// Controls on the page
This is just a general guideline, I did not test the code just wrote from memory, but I will help you get it all working, just start with step one, it gets a little more complicated but I want to do this the right way.
1. I saved Page 1 data into the Database and session variables when the user clicked the Save button. (**Note: I also saved the data that was entered into the database in session variables. Should I really not save the data that is in the database to sessions
variales since this puts too much in the server memory?)
2. On the back button on the second page you will see the following code:
Session[("PrevPage")] = "BACK";
Response.Redirect("~/Page1.aspx");
To get this code to run, I removed edits like the following: <tr> <asp:RequiredFieldValidator CssClass="errorStyle" ID="rqPriordate" Display="Dynamic" runat="server" ControlToValidate="txtlblPriordte2" ErrorMessage="'Prior Date' is a required field."> </asp:RequiredFieldValidator></tr>.
Do you know of any way I can still reconnect edits like I just listed above?
3. When the application returns to web page 1, the code looks like the following:
a.(Session[("PrevPage")]) I used this since my ajax type ahead feature for organization name did not work when the page first loaded. The organization name is one of the grayed out columns when I return from page Do you have any better ideas I could use
to solve this issue? b. The other disabled section is a checkboxlist control that contains all of the suborganization numbers. If there a way to save all the checkbox list control options so the user can see what was selected here?
c. Do you know how I can use the code://CreateDate.Text = (string)Convert.ToDateTime(Session["CreateDate"]);? I need to convert the date to a textbox string but what I tried does not work.
d. Do you know how to change this line of code so that it works correctly? //txtOrgName.BackColor = "gray";
You do not need to carry all the info in your session, just what you need to go an fetch it from the Database when you do the Page_Load event.
<asp:RequiredFieldValidator> is there to enforce the required fields on your form as you well know, is the page not redirecting if you leave that code in place?
Also you really don`t need to put "Back" in your Session, you could use
Request.UrlReferrer.ToString();
This will give you the page that called you.
if (!IsPostBack)
{
// the page that called you
string strRefUrl = Request.UrlReferrer.ToString();
if (strRefUrl == "page2.aspx")
{
// Do Something
}
}
As for loading the page and setting all the various checkboxlist as they were before, I would still use a method to read all the info from the DB and then set the values accordingly.
Sample code to load from DB and assign to Variables and controls:
protected void ReadTheDatabaseToResetForm()
{
int errorCode = 0;
int intmykey = Convert.ToInt32(Session["strMyKey"].ToString());
SqlCommand command = new SqlCommand();
command.CommandText = "[dbo].[MyStordProc_SelectOne_Record]";
command.CommandType = CommandType.StoredProcedure;
SqlConnection staticConnection = new SqlConnection();
staticConnection.ConnectionString = Session["ConnString"].ToString(); ;
command.Connection = staticConnection;
DataTable dtMyDataTable = new DataTable("MyDataTable");
SqlDataAdapter sqlAdapter = new SqlDataAdapter(command);
try
{
SqlParameter iID = new SqlParameter("@iID", SqlDbType.Int, 4);
iID.Value = intmykey;
iID.Direction = ParameterDirection.Input;
command.Parameters.Add(iID);
SqlParameter iErrorCode = new SqlParameter("@iErrorCode", SqlDbType.Int, 4);
iErrorCode.Direction = ParameterDirection.Output;
command.Parameters.Add(iErrorCode);
staticConnection.Open();
sqlAdapter.Fill(dtMyDataTable);
errorCode = (Int32)command.Parameters["@iErrorCode"].Value;
if (errorCode > 1)
throw new Exception("error during call to procedure MyStordProc_SelectOne_Record : " + errorCode);
if (dtMyDataTable.Rows.Count > 0)
{
// Load all the Page Controls here from the DataRow
// this one is an int from the DataBase - sent to a String that you can move to any control.text - Not Null In DB so Nulls Allowed
string strMyString = Convert.ToString(Convert.IsDBNull(dtMyDataTable.Rows[0]["NameOfSqlColumnHere"]) ? (Int32?)null : (Int32?)tMyDataTable.Rows[0]["NameOfSqlColumnHere"]);
// this one is a varchar that can be nulled
string strdescription = Convert.IsDBNull(dtMyDataTable.Rows[0]["NameOfSqlColumnHere"]) ? null : (string)dtMyDataTable.Rows[0]["NameOfSqlColumnHere"];
}
}
catch
{
throw;
}
finally
{
command.Dispose();
}
}
Once Again all this is a matter of personal tastes, I used a stored procedure but you could do it any other way including Linq or Entities.
Here is a label that displays a converted DatimeTime variable.
I have the following additional questions/items to mention:
1. I will definitely obtain the data that is in the database using linq statements and I will not use session variables for those values. I know it is only a good idea to use session variables on a limited basis.
2. On the first webbpage, the button called 'next' inserts data into the database and goes to webpage two. However when a user has returned to page one back after hitting the 'back' button from page 1, I do not want the user to insert new rows into the
database. I only want the user to update the existing row in the main table. How would you handle that code?
Would you have a check like:
if Request.UrlReferrer.ToString == "page1.aspx" then do the update
otherwise to a update statement to the database?
3. You can me a snippet of code for the checkbox list control so I can see what their values are. However, can you give me a better example of how this code would work.? I initially obtain all the values for the checkbox list control from the database.
4. The following is the problem for <asp:RequiredFieldValidator CssClass="errorStyle" ID="rqPriordate" Display="Dynamic" runat="server" ControlToValidate="txtlblPriordte2" ErrorMessage="'create Date' is a required field.">
</as
The problem for page 2 occurs if page 1 looks like the following: protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { LoadPaymentDates(); }
if (Convert.ToString(Session[("PrevPage")]) == "BACK") { do something }
The problem is the formview control on webpage 2, does not have the data loaded into it from the database. This occurs on the initial load of webpage 2.
The formview control currently looks like the following listed below. If I remove the required field validators, the initial load for the formview control works.
The problem I am referring for the required validator, looks like the code below.
Hi, Ok so now I understand a little more, you are using formviews and they are set to editmode by default Basically you need to set the formview datakey and the call a formview.databind for it to load the data. All the stuff I was showing was for a free
form not attached to a formview. It might be easier to do it that way in the long run. Anyways I am on a bus so I can't do much but try resetting the formview datakey and the do a databind on page load That should force the formview to show the current selected
record. I will see if I can post more for you or find you a proper sample of a multi step formview
wendy elizab...
Member
321 Points
390 Posts
web form 2010 button
Jun 20, 2012 03:57 PM|LINK
I am adding some additional code to a C# 2010 web form application that I would like suggestions on how to accomplish the following:
1. I just created an additonal web form page to an existing application so the user can enter more information. I basically want the user to hit the 'back' button so they can return to the original web page and correct the values for up to 4 specific fields. There are two additional fields that the user is not allowed to change.
2. To point the user to the previous page, I do the command, "Response.Redirect("~/Att.aspx"); This works,
3. I want to be able to load all the information the user has entered already when the user returns to this web page. When the user returns to this webpage, the data has already been stored in two tables in the database.
4. Thus I am looking for your suggestion on how to accomplish this goal. I am thinking of the following options:
a. returning the user to the orginal web page in the state it was when they hit the 'next' button to go to the previous webpage. However I do not know how to proceed with this method.
b. Obtain the values from the database, or
c. use session variables. Thus can you tell me what you think the best method would be and examples of code of how you would accomplish this goal?
aabruzzese
Contributor
2806 Points
759 Posts
Re: web form 2010 button
Jun 20, 2012 04:22 PM|LINK
Hi Wendy,
As it stands, when the user hits the back button, what information is displayed on the web page?
Also when you say I would like all the info the user has entered so far to be displayed, is that the info on both pages or only the first one?
As a quick suggestion, I would check out the MultiView control in asp.net, it might well fit the bill.
http://www.aspnettutorials.com/tutorials/controls/using-multiview-control-cs.aspx
wendy elizab...
Member
321 Points
390 Posts
Re: web form 2010 button
Jun 20, 2012 07:44 PM|LINK
The following pertains to your answers:
1. When the user hits the back button, no data is displayed. I have not setup any code for it yet.
2. I only want the information that is entered on the first page to be displayed.
3. The multiview control might have been an option initially. However the first page is already built.
When the user returns to the page I want to display the information that they already entered. How do you suggest I accomplish this goal?
aabruzzese
Contributor
2806 Points
759 Posts
Re: web form 2010 button
Jun 20, 2012 11:35 PM|LINK
I would start by trying it out as is first, have you done that? Also I like to use the record key in the query string and the do a if onm the query string using the key to load all the data from the database. I am on my phone so I can't post any code but I will try to give you idea later. Something like. http://www.myfirstpage.aspx?id=1 So on pageload you ckeck for id and then call you DAL layer and fetch the data and fill the form before displaying it. You could also use session objects and load the form back up, I would tell you ppl will start a long winded debate over something like this, but I get a feeling this is not some huge and or mission critical web app, so technically whatever feels good for you is fine.
wendy elizab...
Member
321 Points
390 Posts
Re: web form 2010 button
Jun 21, 2012 01:41 AM|LINK
I want to mention the following in response to your answer:
1. Passing a query string value back to the first page is not a good idea since there is too much information to pass that needs to be encrypted.
2. Right now in the application, I am passing session variables from the first web page to the second web page. I am thinking it would be a good idea to pass session variables from the second web page to the first web page. Can I somehow reuse the session varirables I setup on the second web page? If not, would I need to create some new session variables on the first web page?
3. I do want to mention all the data I need is already stored in the database.
4. I have tried to load some of the data to the intital web page but I had a few problems. I have the following 6 items that I need to populate data with:
1. The name of the company. This feature needs to be grayed since the user will not be able to change it. (Note: this textbox was originally populated using a type a head feature.
2. The subcompany numbers will be grayed out also since the user can not change this. (Note: this is a initially a checkbox list control where the user selects the subcompanies.)
3. There are two dropdown list controls that had the initial value set to 'N' for no. These two options the user can change when they hit the 'back' button. I want to be able to reload 'Y' or 'N', whatever is in the database.
4. There also is a create date that is split into 2 columns. One column is for month and another column is for year. The user can change this date also once they hit the back button. These two fields initially are loaded with dropdown list values that are loaded in the database.
Thus to start with, I would need to figure out how to reload the first page with the values from the database. I then would need to make the dropdown features work again.
Passing the session variaables back to the first page would be needed since these values are the keys to the database tables.
Can you tell me what you would recommend?
aabruzzese
Contributor
2806 Points
759 Posts
Re: web form 2010 button
Jun 21, 2012 02:02 AM|LINK
Hi,
Ok, so lets say I commit to helping you get this going, lets do this nice and slow that way everything falls into place one domino at a time.
First thing, so we opt for Session Variables.
When you are in the page where you store the Data into the Database you can add the values into Session Objects.
Page 1 -- you stored all your data into the Database when the user clicked the Save button.
protected void SaveMyDataButton_Click(object sender, EventArgs e)
{
SaveDataToDataBase();
Session["DDL_MyDropDownList1Index"] = mydropdownlist1.selectedindex;
Session["DDL_MyDropDownList2Index"] = mydropdownlist2.selectedindex;
Sesssion["txtbox_SomeData"] = mytextbox1.text;
}
The user navigates to Page 2 and then Clicks the Back Button to return to Page1.ASPX
You can now retreive the Session Values and use them to reset your form to how it was before
protected void loadtheform()
{
// Use the Session Variables to read the Database and reload the Textboxes and all other
// Controls on the page
mytextbox1.Text = (string)(Session["txtbox_SomeData"]);
}
This is just a general guideline, I did not test the code just wrote from memory, but I will help you get it all working, just start with step one, it gets a little more complicated but I want to do this the right way.
Also to enable and disable a textbox,
TextBox1.Enabled = false;
TextBox1.BackColor = "Gray";
wendy elizab...
Member
321 Points
390 Posts
Re: web form 2010 button
Jun 21, 2012 05:00 PM|LINK
Hi:
Thank you very much for your help so far!
I want to mention where I am at so far:
1. I saved Page 1 data into the Database and session variables when the user clicked the Save button. (**Note: I also saved the data that was entered into the database in session variables. Should I really not save the data that is in the database to sessions variales since this puts too much in the server memory?)
2. On the back button on the second page you will see the following code:
Session[("PrevPage")] = "BACK";
Response.Redirect("~/Page1.aspx");
To get this code to run, I removed edits like the following: <tr> <asp:RequiredFieldValidator CssClass="errorStyle" ID="rqPriordate" Display="Dynamic" runat="server" ControlToValidate="txtlblPriordte2" ErrorMessage="'Prior Date' is a required field."> </asp:RequiredFieldValidator></tr>.
Do you know of any way I can still reconnect edits like I just listed above?
3. When the application returns to web page 1, the code looks like the following:
protected void Page_Load(object sender, EventArgs e)
{ if (!IsPostBack) { LoadPaymentDates(); }
if (Convert.ToString(Session[("PrevPage")]) == "BACK")
{ txtOrgName.Text = (string)Session["orgname"];
txtOrgName.Enabled = false;
//txtOrgName.BackColor = "gray";
ChkBoxLstPlan.Enabled = false;
//CreateDate.Text = (string)Convert.ToDateTime(Session["CreateDate"]);
ddlPayYear.SelectedIndex = Convert.ToInt32(Session["PaymthIndex"]);
ddlPaymth.SelectedIndex = Convert.ToInt32(Session["PaymentMonthIndex"]);
ddlForm.SelectedIndex = Convert.ToInt32(Session["FormIndex"]);
ddlRpt.SelectedIndex = Convert.ToInt32(Session["RptIndex"]);
ddlPayYear.SelectedValue = Convert.ToString(Session["PayYearValue"]);
ddlPaymth.SelectedValue = Convert.ToString(Session["PayMthValue"]);
ddlvalidForm.SelectedValue = Convert.ToString(Session["validFormValue"]);
ddlDisRpt.SelectedValue = Convert.ToString(Session["DisRptvalue"]); }
}
Comments on item 3:
a.(Session[("PrevPage")]) I used this since my ajax type ahead feature for organization name did not work when the page first loaded. The organization name is one of the grayed out columns when I return from page Do you have any better ideas I could use to solve this issue? b. The other disabled section is a checkboxlist control that contains all of the suborganization numbers. If there a way to save all the checkbox list control options so the user can see what was selected here?
c. Do you know how I can use the code://CreateDate.Text = (string)Convert.ToDateTime(Session["CreateDate"]);? I need to convert the date to a textbox string but what I tried does not work.
d. Do you know how to change this line of code so that it works correctly? //txtOrgName.BackColor = "gray";
aabruzzese
Contributor
2806 Points
759 Posts
Re: web form 2010 button
Jun 21, 2012 05:30 PM|LINK
Hi,
You do not need to carry all the info in your session, just what you need to go an fetch it from the Database when you do the Page_Load event.
<asp:RequiredFieldValidator> is there to enforce the required fields on your form as you well know, is the page not redirecting if you leave that code in place?
Also you really don`t need to put "Back" in your Session, you could use
Request.UrlReferrer.ToString();
This will give you the page that called you.
if (!IsPostBack)
{
// the page that called you
string strRefUrl = Request.UrlReferrer.ToString();
if (strRefUrl == "page2.aspx")
{
// Do Something
}
}
As for loading the page and setting all the various checkboxlist as they were before, I would still use a method to read all the info from the DB and then set the values accordingly.
Sample code to load from DB and assign to Variables and controls: protected void ReadTheDatabaseToResetForm() { int errorCode = 0; int intmykey = Convert.ToInt32(Session["strMyKey"].ToString()); SqlCommand command = new SqlCommand(); command.CommandText = "[dbo].[MyStordProc_SelectOne_Record]"; command.CommandType = CommandType.StoredProcedure; SqlConnection staticConnection = new SqlConnection(); staticConnection.ConnectionString = Session["ConnString"].ToString(); ; command.Connection = staticConnection; DataTable dtMyDataTable = new DataTable("MyDataTable"); SqlDataAdapter sqlAdapter = new SqlDataAdapter(command); try { SqlParameter iID = new SqlParameter("@iID", SqlDbType.Int, 4); iID.Value = intmykey; iID.Direction = ParameterDirection.Input; command.Parameters.Add(iID); SqlParameter iErrorCode = new SqlParameter("@iErrorCode", SqlDbType.Int, 4); iErrorCode.Direction = ParameterDirection.Output; command.Parameters.Add(iErrorCode); staticConnection.Open(); sqlAdapter.Fill(dtMyDataTable); errorCode = (Int32)command.Parameters["@iErrorCode"].Value; if (errorCode > 1) throw new Exception("error during call to procedure MyStordProc_SelectOne_Record : " + errorCode); if (dtMyDataTable.Rows.Count > 0) { // Load all the Page Controls here from the DataRow // this one is an int from the DataBase - sent to a String that you can move to any control.text - Not Null In DB so Nulls Allowed string strMyString = Convert.ToString(Convert.IsDBNull(dtMyDataTable.Rows[0]["NameOfSqlColumnHere"]) ? (Int32?)null : (Int32?)tMyDataTable.Rows[0]["NameOfSqlColumnHere"]); // this one is a varchar that can be nulled string strdescription = Convert.IsDBNull(dtMyDataTable.Rows[0]["NameOfSqlColumnHere"]) ? null : (string)dtMyDataTable.Rows[0]["NameOfSqlColumnHere"]; } } catch { throw; } finally { command.Dispose(); } }Once Again all this is a matter of personal tastes, I used a stored procedure but you could do it any other way including Linq or Entities.
Here is a label that displays a converted DatimeTime variable.
LBL_MyDateTimeLabel.Text = MyDataReader.GetDateTime(0).ToString("yyyy-MM-dd HH:mm:ss");
Here is a little snippet for checkboxes
if (Convert.ToInt32(Session["strstatus"]).Equals(1))
{
chckbxStatus.Checked = true;
}
else
{
chckbxStatus.Checked = false;
}
if (!string.IsNullOrEmpty((string)(Session["strMyCheckBoxListSelectedIndex"])))
{
chlbxlistMyCheckBoxList.ClearSelection();
int myInt = Convert.ToInt32(Session["strMyCheckBoxListSelectedIndex"]);
chlbxlistMyCheckBoxList.Items[myInt].Selected = true;
Session.Remove("strMyCheckBoxListSelectedIndex");
}
I can`t get to all your points for now I will check later this evening when I am at home
wendy elizab...
Member
321 Points
390 Posts
Re: web form 2010 button
Jun 21, 2012 09:42 PM|LINK
Thank you for your continued assistance!!!!
I have the following additional questions/items to mention:
1. I will definitely obtain the data that is in the database using linq statements and I will not use session variables for those values. I know it is only a good idea to use session variables on a limited basis.
2. On the first webbpage, the button called 'next' inserts data into the database and goes to webpage two. However when a user has returned to page one back after hitting the 'back' button from page 1, I do not want the user to insert new rows into the database. I only want the user to update the existing row in the main table. How would you handle that code?
Would you have a check like:
if Request.UrlReferrer.ToString == "page1.aspx" then do the update
otherwise to a update statement to the database?
3. You can me a snippet of code for the checkbox list control so I can see what their values are. However, can you give me a better example of how this code would work.? I initially obtain all the values for the checkbox list control from the database.
4. The following is the problem for <asp:RequiredFieldValidator CssClass="errorStyle" ID="rqPriordate" Display="Dynamic" runat="server" ControlToValidate="txtlblPriordte2" ErrorMessage="'create Date' is a required field."> </as
The problem for page 2 occurs if page 1 looks like the following: protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { LoadPaymentDates(); }
if (Convert.ToString(Session[("PrevPage")]) == "BACK") { do something }
The problem is the formview control on webpage 2, does not have the data loaded into it from the database. This occurs on the initial load of webpage 2.
The formview control currently looks like the following listed below. If I remove the required field validators, the initial load for the formview control works.
The problem I am referring for the required validator, looks like the code below.
<asp:FormView ID="FormView1" runat="server" DataSourceID="LinqDataSource1" AutoGenerateRows="False" HorizontalAlign="Center" DefaultMode="Edit" DataKeyNames="Att" BorderStyle="None" EnableModelValidation="True" > <EditItemTemplate>
<table> <tr> <td> <asp:Label ID="Label2" runat="server" Text='Att ID'></asp:Label> </td>
<td> <asp:Label ID="TextBoxAttid" runat="server" Text='<%# Eval("Att_id") %>'> </asp:Label> </td>
<tr>
<asp:RequiredFieldValidator CssClass="errorStyle" ID="rqPriordate" Display="Dynamic" runat="server" ControlToValidate="txtlblPriordte2" ErrorMessage="'create Date' is a required field."> </asp:RequiredFieldValidator></tr> <tr>
</table> </EditItemTemplate> </asp:FormView>
aabruzzese
Contributor
2806 Points
759 Posts
Re: web form 2010 button
Jun 21, 2012 11:24 PM|LINK
Hi, Ok so now I understand a little more, you are using formviews and they are set to editmode by default Basically you need to set the formview datakey and the call a formview.databind for it to load the data. All the stuff I was showing was for a free form not attached to a formview. It might be easier to do it that way in the long run. Anyways I am on a bus so I can't do much but try resetting the formview datakey and the do a databind on page load That should force the formview to show the current selected record. I will see if I can post more for you or find you a proper sample of a multi step formview