Pass a form field value from one page to another and fit it into a Sql query

Hi all

 I'm trying to do the following and hope you can help

1 User selects a value in a dropDownList(Scheme) on Page1 and then clicks Next button which has a PostBackUrl of Page2

2 on Page2 collect the value that was submitted from Page1 and use this value to query a database. e.g. select * from databasetable where SchemeID = (the value of Scheme Passed from Page1)

Anyone know how I can achieve this?

regards

Chubster

 


it wasn't me, a big boy did it and ran away
0
chubster
7/16/2007 4:15:02 PM
asp.net.web-forms 93655 articles. 6 followers. Follow

21 Replies
837 Views

Similar Articles

[PageSpeed] 5

Hi Chubster,

Using cross page postback, access the PreviousPage property of Page2 to retrieve values from Page1.

More info here and sample here: http://quickstarts.asp.net/QuickStartv20/aspnet/doc/tipstricks/default.aspx


Jason
MCP
ASPNETWorld.com
0
ongj
7/16/2007 4:38:53 PM

Hi,

if you use a PostBackUrl property, ASP.NET loads both old and new pages on the next postback.  The old page (from which you went to new page) is accessible via PreviousPage property from the new page.

You should get values from controls on the old page and initialize your data source.  Note, that if you will need this value later on postbacks, you need to remeber values retrived from the PreviousPage.

-yuriy

0
ysw
7/16/2007 4:38:56 PM

You can call server.transfer("Page2.aspx?WhatEverYouWant=" + dropDown.SelectedValue).

In Page2.aspx, you can add a QueryStringParameter to to the datasource's SelectParameters with the QueryStringField="WhatEverYouWant" 

0
valenumr
7/16/2007 4:47:12 PM

OK, thanks all

I'm trying the example from Asp.net tutorials as suggested, just to see that I can get the relevant values onto the page

In CodeBehind of Page2 at PageLoad I've added
_______
Dim SearchTerm As TextBox
SearchTerm = Page.PreviousPage.FindControl(
"Scheme")
LabelScheme.Text = SearchTerm.Text
_______

In Page2.aspx I've added
________
 <asp:Label ID="LabelScheme" runat="server" Visible="False"></asp:Label>
________

However this generates an error as follows.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 14:             Dim SearchTerm As TextBox
Line 15:             SearchTerm = Page.PreviousPage.FindControl("Scheme")
Line 16:             LabelScheme.Text = SearchTerm.Text

Any ideas? Could this be because the value passed from Page1 belongs to a DropDownList?

 regards

Chubster


 


it wasn't me, a big boy did it and ran away
0
chubster
7/17/2007 9:08:46 AM

Hi Chubster,

two things to your solution:

 

chubster:

_______
Dim SearchTerm As TextBox
SearchTerm = Page.PreviousPage.FindControl(
"Scheme")
LabelScheme.Text = SearchTerm.Text
_______

At first, check allways if the Control you assigned with FindControl() is NOT null, or nothing in VB.

 

If you wont the user can see a controll, use the css-Style attribute instead visible false. When you're using visible false, asp.net wont generate a html output and the control is not present at the client side. Better use Style.Visible=none.

chubster:

In Page2.aspx I've added
________
 <asp:Label ID="LabelScheme" runat="server" Visible="False"></asp:Label>
________

Servus,
Klaus

I haven't the faintest idea, but great many therefrom.
klaus_b@.NET
0
klaus_b
7/17/2007 9:49:14 AM

thanks

Ive changed the label to visible for the time being as suggested and I've added the following code to the code behind page on Page2.

SearchTerm = Page.PreviousPage.FindControl("Scheme")
If Not SearchTerm Is Nothing Then
LabelScheme.Text = SearchTerm.Text
Else
LabelScheme.Text = "NothingPassedToPage"
End If

The result is that the label(LabelScheme) on Page2 produces the text "NothingPassedtoPage" rather than the select value (a number) in the DropDownList("Scheme") on page 1.

Any views?

regards

Chubster

 


it wasn't me, a big boy did it and ran away
0
chubster
7/17/2007 10:08:41 AM

chubster:
SearchTerm = Page.PreviousPage.FindControl("Scheme")

 
If Not Page.PreviousPage Is Nothing Then
      ...
      SearchTerm = CType(Page.PreviousPage.FindControl("Scheme"), TextBox)
      ...
End If
  
 
See if the above modification works...

Jason
MCP
ASPNETWorld.com
0
ongj
7/17/2007 10:14:04 AM

Hi again, 

chubster:

The result is that the label(LabelScheme) on Page2 produces the text "NothingPassedtoPage" rather than the select value (a number) in the DropDownList("Scheme") on page 1.

Simply question: you've added the <PreviuosPage="yourPreviousPage.aspx"> attribute to youre aspx Site shurly?

 


Servus,
Klaus

I haven't the faintest idea, but great many therefrom.
klaus_b@.NET
0
klaus_b
7/17/2007 10:27:16 AM

thanks

I've added

Dim SearchTerm As TextBox

If Not Page.PreviousPage Is Nothing Then

  SearchTerm = CType(Page.PreviousPage.FindControl("Scheme"), TextBox)
'  LabelScheme.Text = SearchTerm.Text
  LabelScheme.Text = "SomethingWasPassedToPage"

Else
  LabelScheme.Text = "NothingPassedToPage"
End If

So, Something is being passed as Page.PreviousPage as the label produces the "SomethingWasPassedtoPage" text.

However if I use  LabelScheme.Text = SearchTerm.Text I get the error as described previously

"Object reference not set to an instance of an object.

Source Error:

Line 16:             If Not Page.PreviousPage Is Nothing Then
Line 17:                 SearchTerm = CType(Page.PreviousPage.FindControl("Scheme"), TextBox)
Line 18:                 LabelScheme.Text = SearchTerm.Text
Line 19:             Else
Line 20:                 LabelScheme.Text = "NothingPassedToPage"


Source File: C:\Inetpub\wwwroot\GPPortal\Portal\NewSubmission_SchemeArea.aspx.vb    Line: 18

regards

chubster


it wasn't me, a big boy did it and ran away
0
chubster
7/17/2007 10:37:47 AM

To your Previous.Page check additonally every control your accessing to check for nothing.

At next check in a debug session if the control is found in the privous page. Maybe is a typing error everywhere on the page.


Servus,
Klaus

I haven't the faintest idea, but great many therefrom.
klaus_b@.NET
0
klaus_b
7/17/2007 10:55:38 AM

klaus_b:
Simply question: you've added the <PreviuosPage="yourPreviousPage.aspx"> attribute to youre aspx Site shurly?

 

 Erm Embarrassed and where do I add this?

regards

chubster


it wasn't me, a big boy did it and ran away
0
chubster
7/17/2007 11:19:35 AM

chubster:

 Erm Embarrassed and where do I add this?

in the Top Section of your aspx site eg

<.... inherits  ="_Default" codebehind="Default.aspx.vb" PreviousPage="PostingSite.aspx">

instead of "PostingSite.aspx" the site where your post from.

Wrote this from my mind, because no VS in front of me. But i'm shure you now where i mean Smile

 


Servus,
Klaus

I haven't the faintest idea, but great many therefrom.
klaus_b@.NET
0
klaus_b
7/17/2007 11:56:56 AM

Hi

Cast the object to a dropdownlist and get the selecteditems text property.

0
nareshvijji
7/17/2007 1:03:51 PM

Hi

thanks

Ok, I've started again with this. The original Page1 and Page2 belong to a MasterPage. Does this effect anything?

 

 I've created a couple of new pages that don't belong to a master just to see if it works without a master and in this case it does.

e.g. I have a text box on Page3 and I click a button and pass the values from that text box to a label on Page4 using something like this in the CodeBehind of Page4

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim SearchTerm As TextBox
        If Not Page.PreviousPage Is Nothing Then
            If Not
Page.PreviousPage.FindControl("Scheme") Is Nothing Then
                SearchTerm = CType(Page.PreviousPage.FindControl("Scheme"), TextBox)
                LabelScheme.Text = SearchTerm.Text
            Else
                LabelScheme.Text = "PagePassedButNoData"
            End If
        Else

            LabelScheme.Text = "NothingPassed"
        End If
    End Sub

 So the question is can you postback to a different page where the pages belong to a master page?

 regards

 chubster

 

 


it wasn't me, a big boy did it and ran away
0
chubster
7/17/2007 1:08:16 PM

chubster:

Ok, I've started again with this. The original Page1 and Page2 belong to a MasterPage. Does this effect anything?

Only when the controls a reside on the MasterPage and NOT on the contentpage.


Servus,
Klaus

I haven't the faintest idea, but great many therefrom.
klaus_b@.NET
0
klaus_b
7/17/2007 1:51:53 PM

chubster:

 So the question is can you postback to a different page where the pages belong to a master page?

Shure, you can do this.

Here is a working sample with two sites, both are contenpages of a masterpage. I post it in C# because VB is not mine.

the SendingPage MarkUp:

1    <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
2    	CodeFile="SendingPage.aspx.cs" Inherits="SendingPage" Title="Untitled Page" %>
3    
4    <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
5    	<asp:TextBox ID="Scheme" runat="server">
6    	</asp:TextBox>
7    	<%--Define the site you're posting to as PostbackUrl--%>
8    	<asp:Button runat="server" ID="SenderButton" Text="Go" PostBackUrl="GettingPage.aspx"
9    		OnClick="SenderButton_Click"></asp:Button>
10   </asp:Content>

 the SendingPage codebehind 

1    public partial class SendingPage : System.Web.UI.Page
2    {
3    	// public string for direct access via PriviousPage
4    	public string sendingString;
5    
6        protected void Page_Load(object sender, EventArgs e)
7        {
8    
9        }
10   
11   	protected void SenderButton_Click(object sender, EventArgs e)
12   	{
13   		// pass the value from the TextBox to the public string
14   		sendingString = Scheme.Text;
15   	}
16   }

__________________________________________________________________________________________ 

the GettingPage MarkUp

1    <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"
2    	CodeFile="GettingPage.aspx.cs" Inherits="GettingPage" Title="Untitled Page" %>
3    
4    <%--Define the Previous Page where is postet from--%>
5    <%@ PreviousPageType VirtualPath="~/SendingPage.aspx" %>
6    <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
7    	<asp:Label ID="LabelScheme" runat="server" Text=""></asp:Label>
8    </asp:Content>

 the GettingPage codebehind

1    public partial class GettingPage : System.Web.UI.Page
2    {
3    	protected void Page_Load(object sender, EventArgs e)
4    	{
5    		// check if PreviousPage NOT is null
6    		if (PreviousPage != null)
7    		{
8    			// access direct the string from the PriviousPage
9    			// without any casting
10   			LabelScheme.Text = PreviousPage.sendingString;
11   		}
12   	}
13   }
14   
More easy it could'nt be Wink
 
Servus,
Klaus

I haven't the faintest idea, but great many therefrom.
klaus_b@.NET
0
klaus_b
7/17/2007 4:06:32 PM

Hi chubster,

Based on my understanding, the problem is caused by the master page. When a master page is applied, you should find the control's parent container first, and then find the control. In your case, you should find the ContentPlaceHolder where the TextBox is nested in, and then find the TextBox in the ContentPlaceHolder.

Please try the following code

 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim SearchTerm As TextBox
        If Not Page.PreviousPage Is Nothing Then
            Dim cp As ContentPlaceHolder = CType(Page.PreviousPage.Master.FindControl("ContentPlaceHolder1"), ContentPlaceHolder)

            If Not cp.FindControl("Scheme") Is Nothing Then
                SearchTerm = CType(cp.FindControl("Scheme"), TextBox)
                LabelScheme.Text = SearchTerm.Text
            Else
                LabelScheme.Text = "PagePassedButNoData"
            End If
        Else
            LabelScheme.Text = "NothingPassed"
        End If


    End Sub

Hope it helps,

Jessica


Jessica Cao
Sincerely,
Microsoft Online Community Support


“Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. ”
0
Jessica
7/18/2007 7:16:07 AM

Hi

thanks all, I've tried the code supplied by Jissica, which gets me a bit further along the line and seems to reference the dropDownList(scheme). However I now receive a typecast error as follows.

___________
Exception Details: System.InvalidCastException: Unable to cast object of type 'System.Web.UI.WebControls.DropDownList' to type 'System.Web.UI.WebControls.TextBox'.

Source Error:

Line 17:
Line 18:                 If Not cp.FindControl("Scheme") Is Nothing Then
Line 19:                     SearchTerm = CType(cp.FindControl("Scheme"), TextBox) 'the error is here
Line 20:                     LabelScheme.Text = SearchTerm.Text
Line 21:                 Else
 
Source File: C:\Inetpub\wwwroot\GPPortal\Portal\NewSubmission_SchemeArea.aspx.vb    Line: 19
__________

  So, any ideas as to what might be wrong here? The DropDownList (Scheme) should pass a number to Page2 that can then be used in a database query.

In the mean time I' might have a go at creating this functionality using the code supplied by Klaus to see whether I can get some values  passed with that.

regards

 Chubster


it wasn't me, a big boy did it and ran away
0
chubster
7/18/2007 10:00:04 AM

Hi Chubster,

Since the Scheme is a DropDownList control, it should be cast to a DropDownList instead of the TextBox, change the code like this

SearchTerm = CType(cp.FindControl("Scheme"), DropDownList)

Hope it helps,

Jessica


Jessica Cao
Sincerely,
Microsoft Online Community Support


“Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread. ”
0
Jessica
7/18/2007 2:03:18 PM

thanks

I think I'm there now, at least with regards to getting the value onto Page2. . Your were right, DropDownList can't be cast as a textbox so on line 1 I changed it to Dim SearchTerm As DropDownList on line 1 and then again change   SearchTerm = CType(cp.FindControl("Scheme"), TextBox) to   SearchTerm = CType(cp.FindControl("Scheme"), DropDownList)

 Here is the code for anyone other noobs that might have similar problems.

1       Dim SearchTerm As DropDownList   
2                If Not Page.PreviousPage Is Nothing Then
3                    Dim cp As ContentPlaceHolder = CType(Page.PreviousPage.Master.FindControl("ContentPlaceHolder1"), ContentPlaceHolder)
4    
5                    If Not cp.FindControl("Scheme") Is Nothing Then
6                        SearchTerm = CType(cp.FindControl("Scheme"), DropDownList)
 
8 LabelScheme.Text = SearchTerm.Text 9 Else 10 LabelScheme.Text = "PagePassedButNoData" 11 End If 12 Else 13 LabelScheme.Text = "NothingPassed" 14 End If

 best regards

Chubster 

 

 


it wasn't me, a big boy did it and ran away
0
chubster
7/18/2007 2:29:13 PM

Thank you so much!!!!!

I have been trying to figure this out for hours!  You do need the to include the .Master before using FindControl.

Thank you again!

Bart

0
bbudz
8/2/2007 7:40:48 PM
Reply:

Similar Artilces:

passing a variable form one page to a sql query in another page
hi, i have a categories page and when the user clicks on a category it is to go to a products page which list all the products in that category. i cant believe it can be that difficult. ive been all round the block on this and have posted a number of messages on another forum but the trail went cold. the story so far... http://www.sitepoint.com/forums/showthread.php?t=396963 any help would be muchly much appreciated! You have several options:  QueryString: You can use querystrings to pass variables from one page to another.  If you are using ASP.NET 2.0, you can use Cross ...

Passing Values from a Web Form to Another Web Form
Hello All! I am trying to pass values from one web form to another web form. I know that there are 3 ways of doing this: queryString, Server.Transfer and Session. I am using the Server.Transfer method. But I am not able to create, in my 2nd web form, an instance of my 1st web form. My 1st Web form is named CallTrack.aspx and my 2nd is named Export.aspx. What I mean is something like this: Public value as CallTrack. I can't create it in my 2nd web form because when the intellisense is displayed, there's no CallTrack in the options. Thanks!   How about using cross-...

Multiple Page Web-forms, without passing earlier pages values to the next one?
I am using RH9, postgreSQL and perl5. Is it possible to get users to submit multiple page web-forms but not to pass values from one form to the next? I would like to store each page to the database server as it is submitted. Also, to build in the process to resume the web-form submission at a later time e.g say there are twent pages to submit and the user stops feeding the forms at the tenth form. I would like to email the user a reminder so he can log back in and start from the eleventh form. Can anyone tell me if this sort of thing is implemented anywhere, so I can study it. Or, can anyone p...

Hi...passing textbox value one form to another form...
how  to pass the one form textbox value to another form datagrid  (pop-up window Datagrid) ...Jani... Hi, refer my article http://www.aspsnippets.com/post/PopUps.aspxMAKMark as Answer if this reply helps youMVP ASP/ASP.NetASP.Net Hosting : Host DepotMy Site : ASPSnippets  To pass data from one form to another form you can use the following:1. TextBox txtName  = (TextBox)Page.PreviousPage.FindControl("textboxid");     textboxid is the id of the TextBox  that is generated at runtime you can find it in  page source of the previous page(Pag...

Submitting Web forms fields to sql database by clicking on SUBMIT FORM and sending the form fields to email box
I have a created or designed a form to be stored in a SQL database table and at the same time when a user clicks on SUBMIT button the form fields will automatically goto the visitor email address immediately. Also i have created a database with tables for each of this forms Pls help i have over 10 forms designed but the problem of submitting them to the table database and the user email address is the challenge now.... You ned to familiarise yourself with the basics of database access in ASP.NET.  There are free tutuorials here: http://quickstarts.asp.net/QuickStartv20/aspnet/doc/da...

Pass values from a web form to another page using a button
I'm trying to do a simple survey, where a user fills out a form and then clicks submit. The button sends them to a new page along with their answers from the form. How do I get it to send the values to the new page? Thanks you can do redirect at the end of button_click handler and pass the parametersAnatoly Lubarsky...

Posting values from one web form to another aspx page
How would I post the values from a form in my application to another form in someone elses application using vb.net? I understand it differs from asp 3.0 as pages in asp.net 1.1 post to themselves and a redirect doesn't post the values to the other form. Any help would be appreciated. If its on the same server try Context.Items["name"] = myText; Server.Transfer("page.aspx"); The application is on a different server. Would/Could/Should I have my aspx page redirect to a asp page which would then collect and transmit the values to the "other" app...

Assign TextBox Value From 1 Form to Another Form on another page
I have searched for days without finding the answer that Im looking for. I have created a marketing request form table called tblRequestForm with a few basic fields. [RequestFormID] , [FormTitle] , [Department] , [YourName]. I also have created another table called tblRequests that has these fields. [RequestID] , [RequestFormID] , [RequestTitle] , [RequestDescription]. I am trying to fill out the RequestForm on page1.aspx then on insert, postback the [RequestFormID] automatically into FormRequest on page2.  I am really new to this and help would be great.~Mickey...

synchronizing chunk of data of one web form for another web form
I'm making a web application. In one web form; i'm taking inputs from user. Now; there is some info given by user in this page which is needed for web form which is going to be displayed next. i want to display that info automatically on that web form so that user doesn't have to re-input that info in this next web form. Info from first page would be inserted into database when user clicks on the submit button. then that next web form would be displayed. and the chunk of info from previous page should be displayed there!!! how can i do this?? cany anybody help?? nobody can help me!! I...

Open web page in IE and populate fields on the form from my web form
To the dot net Knights.  Many humble thanks in advance from a dot net surf. We have an vb application that opens multiple instances of IE object, each to different web pages.  It then takes information from the current record in the app, populates fields on each of the web pages, and them submits the forms.  We are then able to look at the resulting web pages and quickly get the info we're looking for.This prevents us from having to manually navigate to each web site, enter the same information and then wait for the page to open.  If there is ...

Transferring Values From One Web Page To Another Websites Form
I have an interesting scenario at work I have been thinking about for a few days.  We have a little in house built basic CRM that I am trying to get my bosses to let me update and an interesting question came up the other day.  The Question:   Can you write some code that will take a customers shipping information from the CRM and paste it into the fields that our shipping company is looking for with the click of a single button?  So currently our shipping guy has 2 browsers open:  First is our CRM that displays in individual labels the usual information su...

Passing Web Form TextBox value to a SQL Server 2000 Table column field
Community, I am trying to pass a text box value to populate a table column called LastName - see below - using the Update command.  When the below code executes from the Web Form, 'LastName.Text' populates the table column.  I, of course, want the value in the txtLastName.Text field.  Any advice is appreciated! Dim strSQL As New SqlCommand("UPDATE Clients" & _ " SET LastName = 'txtLastName.Text' " & _ " WHERE AccountID =" & txtAccountNo.Text, scnnNW) Rob H. Change: " SET LastName = 'txtLastName.Text' " & _ to " SET LastName...

I am attempting to post to another page and pass a form text box to a sql data source as a query variable.
Hello. I used to use dreamweaver and vbscript to post a form to another page and then use Request.Form to get the variable from the form and put it in a query. I have been trying to do the same in ASP.net. I have managed to get it to work with postback. However when I change the property of the submit button to post the page to another page and specify on the target page a form variable in a data source it does not work. It just reverts to the default. Is there something else I need to set up for it to pick up the form variable from the source page? All help would be gratefully appreciated....

Can my web page with a form submit to other web pages forms?
I was wondering if I created an aspx page that had a form on it that I could use the submit button to submit this form's contents to other web pages forms(servers accepting those form's data). I am thinking this would be a great way to update data on particular web pages without having to actually visit those similar web pages. Any ideas, examples would be much appreciated. Thanks in advance.  Yes you can.  It's called Cross Page Posting: http://msdn2.microsoft.com/en-us/library/ms178139.aspxAlso: http://msdn2.microsoft.com/en-us/library/ms178140.aspx might ...

Web resources about - Pass a form field value from one page to another and fit it into a Sql query - asp.net.web-forms

Chicago police will add more body cameras for officers
Mayor Rahm Emanuel and Chicago Police Superintendent Garry McCarthy said additional cameras will enhance public trust, although their statement ...

Obama visits theatre attacked in Paris
US President Barack Obama, in Paris for the UN climate talks, visits the Bataclan theatre to pay his respects to the 90 people killed there. ...

The Logic Pros: Black Friday/Cyber Monday deals – MIDI keyboards, Lightning/USB mics, iOS synths, plug-ins ...
In this week’s episode of The Logic Pros , we will be taking a short break from the usual routine to stock up on discounted iPad synth apps, ...

Deadspin Up All Night: Bitch You Better Off Voting For Donald Trump
Thank you for your continued support of Deadspin. As you were. Read more...

Turkey to hand over body of dead Russian pilot to Moscow: PM
The body of a Russian pilot killed when his plane was shot down by Turkey last week will be handed over to a Russian representative after being ...

Hunt on for mother of baby buried alive
New York Post Hunt on for mother of baby buried alive Toledo Blade COMPTON, Calif. — Authorities are looking for the mother of a newborn baby ...

A Message For Our Republican Amigos Christie? Trumpf? There's A Better Solution To Your Anguish
Artist Darkblack foresees a Jersey Bounce in New Hampshire The funnest news Saturday night was the announcement that New Hampshire's Union Leader ...

Turkey To Help Stem Flow of Refugee Migrants to Europe
With the ongoing flow of refugee migrants moving from Syria through Turkey and into European Union countries, the EU has asked Turkey to help ...

New Photos Of Princess Charlotte Released By William And Kate As Thank You To Media For Allowing The ...
New photos of Princess Charlotte, the fourth in line to the British throne, have been released by Kensington Palace as a “thank you” to the media ...

Pope Francis is welcomed to the Central African Republic amid recent violence
Pope Francis has arrived in the conflict-torn Central African Republic for the third and final leg of his trip to Africa, brushing aside security ...

Resources last updated: 11/30/2015 1:05:51 AM