Showing posts with label variable. Show all posts
Showing posts with label variable. Show all posts

Thursday, March 29, 2012

Passing values between asp.net pages.

In asp you called a new page and passed any variable information through a query string.
Can some one tell me what the best practice is in asp.net to get information from one asp.net page to another ?

Or at least what the options wereYou can do this exactly as you did in ASP.
If you didn't want to continue using the querystring you could use cookies, sessions, or some other choices. But the querystring in a browser is a querystring in a browser - you can read one or create one just as you always did.

Monday, March 26, 2012

Passing Values from one page to another

I am passing ID of login user as Session variable and i hv to pass id of one more item and that i m passing in query string.But this is not safe, so how can i encrypt and decrypt that id so if user make some changes in id in addressbar of explorer, it didn't get the data.You can use this link to encrypt the data before putting it in a session variable, then decrypt the data again when you want to read it:

Encryption/Decryption with .NET

regards
But i m not using session variable in 2nd case. Ihv to pass the 2nd id in query string. But i want encryption and decruption for that or is that possible that quesry string not visile to end user.

Passing variable between asp login page and the redirected page

Hi All

I have an asp.net 2.0 web with a standard login control

I want to pass some extra variables to the redirected page after the successful login

I just can't get it to work. help much appreciated

--------------------------
Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate

Context.Items.Clear()

Context.Items.Add("UserNamevalue", Me.Login1.UserName)

Context.Items.Add("mydbkeyvalue", 2)

FormsAuthentication.RedirectFromLoginPage("steve", False)

Server.Transfer("~/memberpages/demos.aspx", True)

End If

Catch ex As Exception

Response.Write(ex.Message)

End Try

End Sub

---------------------------------------

In a link button onclick event on the demos.aspx

Me.lblsamupdate.Text = "Context " & Context.Items("UserNamevalue").ToString

I get error 'Object reference not set to an instance of an object'

Why???Hello Steve,

did you check that u have this variable in the context in receiver?

--
WBR,
Michael Nemtsev [.NET/C# MVP] :: blog: http://spaces.live.com/laflour
"The greatest danger for most of us is not that our aim is too high and we
miss it, but that it is too low and we reach it" (c) Michelangelo

SHi All
S>
SI have an asp.net 2.0 web with a standard login control
S>
SI want to pass some extra variables to the redirected page after the
Ssuccessful login
S>
SI just can't get it to work. help much appreciated
S>
S---------------------
S------
S>
SProtected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As
SSystem.Web.UI.WebControls.AuthenticateEventArgs) Handles
SLogin1.Authenticate
S>
SContext.Items.Clear()
S>
SContext.Items.Add("UserNamevalue", Me.Login1.UserName)
S>
SContext.Items.Add("mydbkeyvalue", 2)
S>
SFormsAuthentication.RedirectFromLoginPage("steve", False)
S>
SServer.Transfer("~/memberpages/demos.aspx", True)
S>
SEnd If
S>
SCatch ex As Exception
S>
SResponse.Write(ex.Message)
S>
SEnd Try
S>
SEnd Sub
S>
S---------------------
S-------------------
S>
SIn a link button onclick event on the demos.aspx
S>
SMe.lblsamupdate.Text = "Context " &
SContext.Items("UserNamevalue").ToString
S>
SI get error 'Object reference not set to an instance of an object'
S>
SWhy???
S>
Steve.
I don't see how you can expect this to work:

FormsAuthentication.RedirectFromLoginPage("steve", False)
Server.Transfer("~/memberpages/demos.aspx", True)

Your first line causes the browser to request the redirect page.
the second line (Server.Transfer) will never execute.

Also, you could either stick the items into a cookie(s) or put them in
Session.

-- Peter
// Abandon all hope, ye who enter here.
http://www.eggheadcafe.com
unBlog: http://petesbloggerama.blogspot.com
BlogMetaFinder: http://www.blogmetafinder.com
"Steve" wrote:

Quote:

Originally Posted by

Hi All
>
I have an asp.net 2.0 web with a standard login control
>
I want to pass some extra variables to the redirected page after the successful login
>
I just can't get it to work. help much appreciated
>
--------------------------
Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
>
Context.Items.Clear()
>
Context.Items.Add("UserNamevalue", Me.Login1.UserName)
>
Context.Items.Add("mydbkeyvalue", 2)
>
FormsAuthentication.RedirectFromLoginPage("steve", False)
>
Server.Transfer("~/memberpages/demos.aspx", True)
>
End If
>
Catch ex As Exception
>
Response.Write(ex.Message)
>
End Try
>
End Sub
>
---------------------------------------
>
In a link button onclick event on the demos.aspx
>
Me.lblsamupdate.Text = "Context " & Context.Items("UserNamevalue").ToString
>
I get error 'Object reference not set to an instance of an object'
>
>
>
Why???
>

Passing Variable Across Secure Pages

Hey Bros:

I'm new to asp.net obviously, and am working on trying to put together my first website. I need help passing variables across multiple forms then trying to query a sql database based on the data which is passed.

What I have is
page one, datalist with a button when clicked will redirect to a page in a directory protected using forms authentication, user will be redirected to log in, once logged in the are redirected to the original destination page.

page two, will show the items, and details of the page which corresponds to the button the visitor originally choose.

I know I basicly have to create something to grab the value on the original page, and then on the destination page create something to grab the value, then perform an SQL statement agianst the value which was orignally grabbed from the first page. I just cannot find code which I can understand to do this. Any help would be greatly appreciated!Well one step at a time will take you far places...

You can easily preserve the data in a form item by enabling viewstate on the form by adding the following syntax enabledviewstate="true" This uses more system resources though and should not be enabled for form items that do not need it.

You were saying that you want to pass data from here to there etc... Well in asp.net you really do not have to and can code your entire program into one asp.net which eliminates passing values to and from. Ever hear about asp.net panels? A good book I would recommend is ASP.NET UNLEASHED by: Stephen Walther, if you are just starting out... I will track this thread to see if you have any other Q's...

passing variable from child to parent - possible ?

I have a main form, and i have another form i need to call on a button
press,
then id like the result of the child form to pass data back to the parent -
without losing any data previously entered
on the parent - is this possible ? ( my main parent window is starting to
get quite cluttered)

cheers

markmark wrote:
> I have a main form, and i have another form i need to call on a button
> press,
> then id like the result of the child form to pass data back to the parent -
> without losing any data previously entered
> on the parent - is this possible ? ( my main parent window is starting to
> get quite cluttered)
> cheers
> mark

The problem is in not losing the "parent" data... Are these windows open
in the same browser window or are you opening the "child" in a new
window? If its the same just save their existing data, in a
db/viewstate/session/etc, and then when you reload it retrieve it.
If not you will have to force the "parent" to postback to get it to
refresh, and with the viewstate enabled you should get the pre-entered
data to remain

--
Curt Christianson
site: http://www.darkfalz.com
blog: http://blog.darkfalz.com
Mark,

The standard way is to call javascript method showModalDialog for the child
form. The child form can pass back data in javascript window.returnValue
property which the parent form will get as a return value of the
showModalDialog call.

Eliyahu

"mark" <mark@.remove.com> wrote in message
news:1122386021.4716.0@.spandrell.news.uk.clara.net ...
> I have a main form, and i have another form i need to call on a button
> press,
> then id like the result of the child form to pass data back to the
parent -
> without losing any data previously entered
> on the parent - is this possible ? ( my main parent window is starting to
> get quite cluttered)
> cheers
> mark
Mark,

The standard way is to call javascript method showModalDialog for the child
form. The child form can pass back data in javascript window.returnValue
property which the parent form will get as a return value of the
showModalDialog call.

Eliyahu

"mark" <mark@.remove.com> wrote in message
news:1122386021.4716.0@.spandrell.news.uk.clara.net ...
> I have a main form, and i have another form i need to call on a button
> press,
> then id like the result of the child form to pass data back to the
parent -
> without losing any data previously entered
> on the parent - is this possible ? ( my main parent window is starting to
> get quite cluttered)
> cheers
> mark
> The problem is in not losing the "parent" data... Are these windows open
> in the same browser window or are you opening the "child" in a new
> window? If its the same just save their existing data, in a
> db/viewstate/session/etc, and then when you reload it retrieve it.
> If not you will have to force the "parent" to postback to get it to
> refresh, and with the viewstate enabled you should get the pre-entered
> data to remain
> --
> Curt Christianson
> site: http://www.darkfalz.com
> blog: http://blog.darkfalz.com

looks like ill be forced to save on opening the child, either that i
redesign the whole form to be more modular
problem is - i have to pass an ID to the child that doesnt exist until the
parent is saved - so things are getting more complicated
than in reality they should be

cheers

mark
"Eliyahu Goldin" <removemeegoldin@.monarchmed.com> wrote in message
news:OvYQHtekFHA.1464@.TK2MSFTNGP14.phx.gbl...
> Mark,
> The standard way is to call javascript method showModalDialog for the
child
> form. The child form can pass back data in javascript window.returnValue
> property which the parent form will get as a return value of the
> showModalDialog call.
> Eliyahu
got any examples ?

thanks

mark
> The problem is in not losing the "parent" data... Are these windows open
> in the same browser window or are you opening the "child" in a new
> window? If its the same just save their existing data, in a
> db/viewstate/session/etc, and then when you reload it retrieve it.
> If not you will have to force the "parent" to postback to get it to
> refresh, and with the viewstate enabled you should get the pre-entered
> data to remain
> --
> Curt Christianson
> site: http://www.darkfalz.com
> blog: http://blog.darkfalz.com

looks like ill be forced to save on opening the child, either that i
redesign the whole form to be more modular
problem is - i have to pass an ID to the child that doesnt exist until the
parent is saved - so things are getting more complicated
than in reality they should be

cheers

mark
"Eliyahu Goldin" <removemeegoldin@.monarchmed.com> wrote in message
news:OvYQHtekFHA.1464@.TK2MSFTNGP14.phx.gbl...
> Mark,
> The standard way is to call javascript method showModalDialog for the
child
> form. The child form can pass back data in javascript window.returnValue
> property which the parent form will get as a return value of the
> showModalDialog call.
> Eliyahu
got any examples ?

thanks

mark

passing variable from child to parent - possible ?

I have a main form, and i have another form i need to call on a button
press,
then id like the result of the child form to pass data back to the parent -
without losing any data previously entered
on the parent - is this possible ? ( my main parent window is starting to
get quite cluttered)

cheers

markmark wrote:
> I have a main form, and i have another form i need to call on a button
> press,
> then id like the result of the child form to pass data back to the parent -
> without losing any data previously entered
> on the parent - is this possible ? ( my main parent window is starting to
> get quite cluttered)
> cheers
> mark

The problem is in not losing the "parent" data... Are these windows open
in the same browser window or are you opening the "child" in a new
window? If its the same just save their existing data, in a
db/viewstate/session/etc, and then when you reload it retrieve it.
If not you will have to force the "parent" to postback to get it to
refresh, and with the viewstate enabled you should get the pre-entered
data to remain

--
Curt Christianson
site: http://www.darkfalz.com
blog: http://blog.darkfalz.com

Passing Variable Between Webforms

I'm a little new to this .NET jazz so my question may be a little trivial but how do you pass variables between webforms?If you are coming from an ASP background, it's pretty much the same.. you can pass variables with the querystring, Server.Transfer(), Session, or a datbase solution. In .NET you can also use the Cache object if the data is of Application scope (everyone is using the same value).

passing variable from code behind to function in javascript

Just wondering if someone could provide an example of passing a variable from
the code behind to javascript in vb. I want to have one control have focus
with the page loading with one condition and have another control with focus
after the page loads from a different condition. A gets set in the code
aspx.vb file and the script might look something like,
<script language="javascript">
function DoHighlight(a)
{
if a = 1 {
document.Form1.dr_lst_system.focus();
}
else
{
Form1.textbox1.focus();
}
}
</script
thanks.
--
Paul G
Software engineer.Hi Paul,

It is impossible to pass a variable value from the server to the client.
Server-side code executes on the server. Client-side code executes on the
client.

That said, it is certainly possible to WRITE client-side scripting code
(which will be executed on the client) dynamically from the server side.
That is what you need to do.

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
Ambiguity has a certain quality to it.

"Paul" <Paul@.discussions.microsoft.com> wrote in message
news:1BB64CF9-9547-4DF0-9556-E2F88CE79ECA@.microsoft.com...
> Just wondering if someone could provide an example of passing a variable
> from
> the code behind to javascript in vb. I want to have one control have
> focus
> with the page loading with one condition and have another control with
> focus
> after the page loads from a different condition. A gets set in the code
> aspx.vb file and the script might look something like,
> <script language="javascript">
> function DoHighlight(a)
> {
> if a = 1 {
> document.Form1.dr_lst_system.focus();
> }
> else
> {
> Form1.textbox1.focus();
> }
> }
> </script>
>
> thanks.
> --
> Paul G
> Software engineer.
Paul,

This is normally done with hidden input controls. Put a line

<input type=hidden runat=server id=inhA
in the .aspx file. If you switch from Html view to Design and back, you will
find in the code-behind a definition for inhA as an obyect of type
System.Web.UI.HtmlControls.HtmlInputHidden.

You can now set inhA.Value="1" on server side and check if (inhA.value ==
"1") on client side.

Eliyahu

"Paul" <Paul@.discussions.microsoft.com> wrote in message
news:1BB64CF9-9547-4DF0-9556-E2F88CE79ECA@.microsoft.com...
> Just wondering if someone could provide an example of passing a variable
from
> the code behind to javascript in vb. I want to have one control have
focus
> with the page loading with one condition and have another control with
focus
> after the page loads from a different condition. A gets set in the code
> aspx.vb file and the script might look something like,
> <script language="javascript">
> function DoHighlight(a)
> {
> if a = 1 {
> document.Form1.dr_lst_system.focus();
> }
> else
> {
> Form1.textbox1.focus();
> }
> }
> </script>
>
> thanks.
> --
> Paul G
> Software engineer.
Hi thanks for the response. Here is what I have but it does not seem to be
working. In the Java script I have
<form id="Form1" method="post" runat="server">
<input type="hidden" runat="server" id="inhA" NAME="inhA">
<script language="javascript" event="onload" for="window">
if (inhA.value == 0)
{Form1.dr_tx_names.focus();}
if (inhA.value == 1)
{Form1.dr_lst_system.focus();}
</script>and in the aspx.vb file I have
in page load event
If Not Page.IsPostBack Then 'only first time page loads
Me.inhA.Value = 0
and in a dropdown event select-causes the page to reload I have
Me.inhA.Value = 1
**************so I want one control two have focus if inhA = 0 and the other
to have focus if inhA = 1.
thanks for the information.
--
Paul G
Software engineer.

"Eliyahu Goldin" wrote:

> Paul,
> This is normally done with hidden input controls. Put a line
> <input type=hidden runat=server id=inhA>
> in the .aspx file. If you switch from Html view to Design and back, you will
> find in the code-behind a definition for inhA as an obyect of type
> System.Web.UI.HtmlControls.HtmlInputHidden.
> You can now set inhA.Value="1" on server side and check if (inhA.value ==
> "1") on client side.
> Eliyahu
> "Paul" <Paul@.discussions.microsoft.com> wrote in message
> news:1BB64CF9-9547-4DF0-9556-E2F88CE79ECA@.microsoft.com...
> > Just wondering if someone could provide an example of passing a variable
> from
> > the code behind to javascript in vb. I want to have one control have
> focus
> > with the page loading with one condition and have another control with
> focus
> > after the page loads from a different condition. A gets set in the code
> > aspx.vb file and the script might look something like,
> > <script language="javascript">
> > function DoHighlight(a)
> > {
> > if a = 1 {
> > document.Form1.dr_lst_system.focus();
> > }
> > else
> > {
> > Form1.textbox1.focus();
> > }
> > }
> > </script>
> > thanks.
> > --
> > Paul G
> > Software engineer.
>
On Wed, 29 Jun 2005 11:02:04 -0700, Paul wrote:

> Just wondering if someone could provide an example of passing a variable from
> the code behind to javascript in vb. I want to have one control have focus
> with the page loading with one condition and have another control with focus
> after the page loads from a different condition. A gets set in the code
> aspx.vb file and the script might look something like,
> <script language="javascript">
> function DoHighlight(a)
> {
> if a = 1 {
> document.Form1.dr_lst_system.focus();
> }
> else
> {
> Form1.textbox1.focus();
> }
> }
> </script>
>
> thanks.
Something like
if(<%=a%> = 1) will work (a is a server-side variable)
ok thanks for the information.
--
Paul G
Software engineer.

"intrader" wrote:

> On Wed, 29 Jun 2005 11:02:04 -0700, Paul wrote:
> > Just wondering if someone could provide an example of passing a variable from
> > the code behind to javascript in vb. I want to have one control have focus
> > with the page loading with one condition and have another control with focus
> > after the page loads from a different condition. A gets set in the code
> > aspx.vb file and the script might look something like,
> > <script language="javascript">
> > function DoHighlight(a)
> > {
> > if a = 1 {
> > document.Form1.dr_lst_system.focus();
> > }
> > else
> > {
> > Form1.textbox1.focus();
> > }
> > }
> > </script>
> > thanks.
> Something like
> if(<%=a%> = 1) will work (a is a server-side variable)

passing variable from child to parent - possible ?

I have a main form, and i have another form i need to call on a button
press,
then id like the result of the child form to pass data back to the parent -
without losing any data previously entered
on the parent - is this possible ? ( my main parent window is starting to
get quite cluttered)
cheers
markmark wrote:
> I have a main form, and i have another form i need to call on a button
> press,
> then id like the result of the child form to pass data back to the parent
-
> without losing any data previously entered
> on the parent - is this possible ? ( my main parent window is starting to
> get quite cluttered)
> cheers
> mark
>
The problem is in not losing the "parent" data... Are these windows open
in the same browser window or are you opening the "child" in a new
window? If its the same just save their existing data, in a
db/viewstate/session/etc, and then when you reload it retrieve it.
If not you will have to force the "parent" to postback to get it to
refresh, and with the viewstate enabled you should get the pre-entered
data to remain
Curt Christianson
site: http://www.darkfalz.com
blog: http://blog.darkfalz.com
Mark,
The standard way is to call javascript method showModalDialog for the child
form. The child form can pass back data in javascript window.returnValue
property which the parent form will get as a return value of the
showModalDialog call.
Eliyahu
"mark" <mark@.remove.com> wrote in message
news:1122386021.4716.0@.spandrell.news.uk.clara.net...
> I have a main form, and i have another form i need to call on a button
> press,
> then id like the result of the child form to pass data back to the
parent -
> without losing any data previously entered
> on the parent - is this possible ? ( my main parent window is starting to
> get quite cluttered)
> cheers
> mark
>
> >
> The problem is in not losing the "parent" data... Are these windows open
> in the same browser window or are you opening the "child" in a new
> window? If its the same just save their existing data, in a
> db/viewstate/session/etc, and then when you reload it retrieve it.
> If not you will have to force the "parent" to postback to get it to
> refresh, and with the viewstate enabled you should get the pre-entered
> data to remain
> --
> Curt Christianson
> site: http://www.darkfalz.com
> blog: http://blog.darkfalz.com
looks like ill be forced to save on opening the child, either that i
redesign the whole form to be more modular
problem is - i have to pass an ID to the child that doesnt exist until the
parent is saved - so things are getting more complicated
than in reality they should be
cheers
mark
"Eliyahu Goldin" <removemeegoldin@.monarchmed.com> wrote in message
news:OvYQHtekFHA.1464@.TK2MSFTNGP14.phx.gbl...
> Mark,
> The standard way is to call javascript method showModalDialog for the
child
> form. The child form can pass back data in javascript window.returnValue
> property which the parent form will get as a return value of the
> showModalDialog call.
> Eliyahu
>
got any examples ?
thanks
mark

Passing variable from Sub to Sub

How do I pass the value to

Public Sub DeliverFile(ByVal Page As System.Web.UI.Page, _
ByVal Data() As Byte, ByVal Type As String, _
ByVal Length As Integer, _
Optional ByVal DownloadFileName As String = "")

Suppose I have a sub that get the connection as below?

sub connect(sender As Object, e As EventArgs)
dim cnn as string = "dsn=fyp; uid=root; pwd="
dim oconn as new odbcconnection(cnn)
dim sql as string
sql = "Select * From ReportSubmission Where StudentID = 'WeiSiong';"
dim cmd as odbccommand
cmd = new odbccommand(sql, oconn)
oconn.open
cmd.executereader
oconn.close
end sub
You have to explain yourself. What values are you getting from database, what kind of data types are they. What do want to do with these values and your method?
To get the data and put it into a dataset (a collection of data that ASP.NEt controls natively bind to) you would use the following function:

Function GetData(ByVal StudentID As String) As System.Data.DataSet
Dim connectionString As String = "Insert your connection string here"
Dim dbConnection As System.Data.IDbConnection = New System.Data.OleDb.OleDbConnection(connectionString)
Dim query As String = "SELECT * FROM ReportSubmission WHERE StudentID = @.StudentID"
Dim dbCommand As System.Data.IDbCommand = New System.Data.OleDb.OleDbCommand
dbCommand.CommandText = query
dbCommand.Connection = dbConnection

Dim paramSID As System.Data.IDataParameter = New System.Data.OleDb.OleDbParameter
paramSID.ParameterName = "@.StudentID"
paramSID.Value = StudentID
paramSID.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(paramSID)

Dim dataAdapter As System.Data.IDbDataAdapter = New System.Data.OleDb.OleDbDataAdapter
dataAdapter.SelectCommand = dbCommand
Dim ds As System.Data.DataSet = New System.Data.DataSet
dataAdapter.Fill(dataSet)
Return ds
End Function

Then, in order to access the dataset within your code you would call the function as follows


dim yourdata as string = GetData("WeiSiong").tables(0).rows(0).item("Name of column in the database that you want to read from")

passing variable from Popup

Whats the best way to pass a variable from a popup to the current page
(without a postback on the current page).
I have a form on 'page1' with various text input boxes. One box contains an
image URL. To select the url , the user can click on a browse button to open
a url chooser pop up ('page2'). I want the url that is selected in 'page2'
to be posted back to 'page1' and displayed in the input box, without losing
the values a user has already input in the other textboxes on page1.
I can use the 'previouspage' method, but I don't think this can work with
popups can it? I don't want the user to lose any of the other textboxes if
they have to browse to the url chooser page then return to the page1.
hopefully that all makes sense.
JJyes or I was using:
btn_browse.Attributes.Add("onclick", "java script:window.open('..etc
"Mark Rae" <mark@.markNOSPAMrae.com> wrote in message
news:uJ5DjU0$GHA.3536@.TK2MSFTNGP03.phx.gbl...
> "JJ" <abc@.xyz.com> wrote in message
> news:eEdelQ0$GHA.4680@.TK2MSFTNGP04.phx.gbl...
>
> When you say 'popup', do you mean you're using showModalDialog...?
>
"JJ" <abc@.xyz.com> wrote in message
news:eEdelQ0$GHA.4680@.TK2MSFTNGP04.phx.gbl...

> Whats the best way to pass a variable from a popup to the current page
> (without a postback on the current page).
When you say 'popup', do you mean you're using showModalDialog...?
Write this code, on click event on button leads to close the popup.
/* Start from here*/
String sURL =’’ // selected url
string strScript = "<SCRIPT>window.opener.SendBackURLTOMainPage(‘ + sURL
+’); window.opener.document.forms(0).submit();
self.close();</SCRIPT>";
Page.RegisterClientScriptBlock("ClosePopup", strScript);
/* Ends here*/
Declare the this javascript function SendBackURLTOMainPage(val) in the main
page (aspx)
hdnURL is the hidden variable which store the selected URL from the popup
page.
function SendBackURLTOMainPage (val)
{
document.getElementById("hdnURL").innerText = val;
}
all the best,
Lokesh
"JJ" wrote:

> Whats the best way to pass a variable from a popup to the current page
> (without a postback on the current page).
> I have a form on 'page1' with various text input boxes. One box contains a
n
> image URL. To select the url , the user can click on a browse button to op
en
> a url chooser pop up ('page2'). I want the url that is selected in 'page2'
> to be posted back to 'page1' and displayed in the input box, without losin
g
> the values a user has already input in the other textboxes on page1.
> I can use the 'previouspage' method, but I don't think this can work with
> popups can it? I don't want the user to lose any of the other textboxes if
> they have to browse to the url chooser page then return to the page1.
>
> hopefully that all makes sense.
> JJ
>
>
Thanks Lokesh. But is there any way of doing this in ASP.net rather than
javascript?
"Lokesh Reddy" <Lokesh Reddy@.discussions.microsoft.com> wrote in message
news:662ECFA3-6669-4DC7-97CF-334B00111516@.microsoft.com...
> Write this code, on click event on button leads to close the popup.
> /* Start from here*/
> String sURL ='' // selected url
> string strScript = "<SCRIPT>window.opener.SendBackURLTOMainPage(' + sURL
> +'); window.opener.document.forms(0).submit();
> self.close();</SCRIPT>";
> Page.RegisterClientScriptBlock("ClosePopup", strScript);
> /* Ends here*/
>
> Declare the this javascript function SendBackURLTOMainPage(val) in the
> main
> page (aspx)
> hdnURL is the hidden variable which store the selected URL from the popup
> page.
> function SendBackURLTOMainPage (val)
> {
> document.getElementById("hdnURL").innerText = val;
> }
> all the best,
> Lokesh
> "JJ" wrote:
>
Also,
If I wanted to pass the variable into different textboxes, (depending on
which 'browse' button was clicked) is there a way of doing this?
JJ
"JJ" <abc@.xyz.com> wrote in message
news:e0Vl2y0$GHA.1464@.TK2MSFTNGP02.phx.gbl...
> Thanks Lokesh. But is there any way of doing this in ASP.net rather than
> javascript?
> "Lokesh Reddy" <Lokesh Reddy@.discussions.microsoft.com> wrote in message
> news:662ECFA3-6669-4DC7-97CF-334B00111516@.microsoft.com...
>
"JJ" <abc@.xyz.com> wrote in message
news:e0Vl2y0$GHA.1464@.TK2MSFTNGP02.phx.gbl...

> Thanks Lokesh. But is there any way of doing this in ASP.net rather than
> javascript?
No. ASP.NET is server-side, and can't obviously open windows client-side -
you need JavaScript for that.
Ok I've been trying to do this but without success:
I have a button on my urlChooser page:
protected void Button1_OnClick(object sender, System.EventArgs e)
{
String sURL = this.ImageURL_txtbox.Text; // selected url
string strScript = "<SCRIPT>window.opener.SendBackURLTOMainPage('" + sURL +
"'); window.opener.document.forms(0).submit();self.close();</SCRIPT>";
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"ClosePopup",
strScript);
}
and the javascript function in my main page is:
<script type="text/javascript">
function SendBackURLTOMainPage (val)
{
document.getElementById('TextBox1').value=val;
}
</script>
However, the urlChooser page comes up with an error when I click the button,
and the urlChooser window doesn't close. The error says there's an invald
character in this line:
<SCRIPT>window.opener.SendBackURLTOMainPage('/WebSite1/Uploads/XPS1/admin2/C
ivic_photo.gif');
window.opener.document.forms(0).submit();self.close();</SCRIPT>
(forgive me but I'm not too familiar with javascript)
JJ
"Lokesh Reddy" <Lokesh Reddy@.discussions.microsoft.com> wrote in message
news:662ECFA3-6669-4DC7-97CF-334B00111516@.microsoft.com...
> Write this code, on click event on button leads to close the popup.
> /* Start from here*/
> String sURL ='' // selected url
> string strScript = "<SCRIPT>window.opener.SendBackURLTOMainPage(' + sURL
> +'); window.opener.document.forms(0).submit();
> self.close();</SCRIPT>";
> Page.RegisterClientScriptBlock("ClosePopup", strScript);
> /* Ends here*/
>
> Declare the this javascript function SendBackURLTOMainPage(val) in the
> main
> page (aspx)
> hdnURL is the hidden variable which store the selected URL from the popup
> page.
> function SendBackURLTOMainPage (val)
> {
> document.getElementById("hdnURL").innerText = val;
> }
> all the best,
> Lokesh
> "JJ" wrote:
>
Found the problem, the single quotes need to be double quotes. Sorry. Still
learning...
"JJ" <abc@.xyz.com> wrote in message
news:ObG8i62$GHA.2328@.TK2MSFTNGP02.phx.gbl...
> Ok I've been trying to do this but without success:
> I have a button on my urlChooser page:
> protected void Button1_OnClick(object sender, System.EventArgs e)
> {
> String sURL = this.ImageURL_txtbox.Text; // selected url
> string strScript = "<SCRIPT>window.opener.SendBackURLTOMainPage('" + sURL
> + "'); window.opener.document.forms(0).submit();self.close();</SCRIPT>";
> Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"ClosePopup",
> strScript);
> }
> and the javascript function in my main page is:
> <script type="text/javascript">
> function SendBackURLTOMainPage (val)
> {
> document.getElementById('TextBox1').value=val;
> }
> </script>
>
> However, the urlChooser page comes up with an error when I click the
> button, and the urlChooser window doesn't close. The error says there's an
> invald character in this line:
> <SCRIPT>window.opener.SendBackURLTOMainPage('/WebSite1/Uploads/XPS1/admin2
/Civic_photo.gif');
> window.opener.document.forms(0).submit();self.close();</SCRIPT>
>
> (forgive me but I'm not too familiar with javascript)
>
> JJ
>
>
>
>
>
> "Lokesh Reddy" <Lokesh Reddy@.discussions.microsoft.com> wrote in message
> news:662ECFA3-6669-4DC7-97CF-334B00111516@.microsoft.com...
>

Passing variable into ASCX in vb.net

I have an ASCX which I have as the header for all my pages in my site.

In this ASCX page I determine which banner to show. It's been working great so far except now I have to add the capabilities of "zones" for my pages. This means I need to pass a variable to it.

Does anyone have an example of this ? I can't seem to find anything. I'm assuming this can be done.

Thanks alot
mike123Create a public field in the user control. Then on the page that you are including the usercontrol, add the property and the value to the HTML declaration to pass in the value to the usercontrol.

So if you create a public field like so in your usercontrol:

VB:
Public myProperty As String

C#:
public string myProperty;

Then in the HTML portion of the page that has the usercontrol on it, you would have:

<[TagPrefix]:[TagName] ID="myUserControl1" myProperty="This is what I am passing." runat="server" /
Now when the control is rendered, the public field myProperty that was defined in the UserControl has the value of 'This is what I am passing.', without the single quotes.

The TagPrefix and the TagName is defined in the Register tag at the top of the page. If you are using Visual Studio, it will automatically handle that for you when you drag the user control onto the page. All you need to to is put in the myProperty portion in the appropriate tag.
You may add a property in your usercontrol class.
Hi Jimmy,

Thanks for the response. Would you happen to have an example of how this is done? I haven't attempted this before and am unsure how to go about doing that

thanks again
In your ascx class, add this code before page_load event:
Assume your usercontrol called "usercontrol1"
In usercontrol1.ascx.vb


Dim strTest As String = ""
Public Property Test() As String
Get
Return strTest
End Get

Set(ByVal Value As String)
strTest = Value
End Set

In aspx.vb


Protected WithEvents propertyTest As usercontrol1

Private Shadows Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
usercontrol1.Test = "Test"
End Sub

Passing Variable To Controls

If we have a web page in which any simple control is present for example a TextBox

<asp:TextBoxID="TextBox1"runat="server"Text=""></asp:TextBox>

Now in code file a public variable is defined like

publicstring txtValue ="Khan";

Now I want to assign thetxtValue inText filed of TextBox Just like

<asp:TextBoxID="TextBox1"runat="server"Text="<%=txtValue%>"></asp:TextBox>

But this approach is not working.

Can anyone tell it?

Modify your markup to:

<asp:TextBox ID="TextBox1" runat="server" Text='<%# GetValue %>' />
 Then you should make an at least protected function in your code behind to return the string:
 
protected string GetValue(){return txtValue;}

I have tried it but it is getting error.

Please check it on you own side.


This syntax should work. I've used it a dozen times in my apps.

What is the error you're getting?


Default.aspx.cs

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

publicpartialclass_Default : System.Web.UI.Page

{

privatestring txtValue ="Zeeshan";protectedstring GetValue()

{

return txtValue;

}

}

Default.aspx

<%@.PageLanguage="C#"AutoEventWireup="true"CodeFile="Default.aspx.cs"Inherits="_Default"Debug="true" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>Untitled Page</title>

</head>

<body>

<formid="form1"runat="server">

<div>

<asp:TextBoxID="TextBox1"runat="server"Text="<%# GetValue %>"></asp:TextBox>

</div>

</form>

</body>

</html>

And the error which I am getting is

Error 1 The best overloaded method match for 'System.Convert.ToString(object, System.IFormatProvider)' has some invalid arguments D:\New Project\dawateislamix.net\Default.aspx 12

Error 2 Argument '1': cannot convert from 'method group' to 'object' D:\New Project\dawateislamix.net\Default.aspx 12


Can you try with<asp:TextBoxID="TextBox1"runat="server"Text="<%# GetValue() %>"></asp:TextBox>


Modify your html as follows:

<asp:TextBoxID="TextBox1"runat="server"Text="<%# GetValue() %>"></asp:TextBox>


There is not any error now.

But still the value is not passed to the control.


Pls try to set the value in

Page_Load() event.

txtValue ="Zeeshan" ;


Default2.aspx

<%@.PageLanguage="C#"AutoEventWireup="true"CodeFile="Default2.aspx.cs"Inherits="Default2" %>

<!DOCTYPEhtmlPUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<htmlxmlns="http://www.w3.org/1999/xhtml">

<headrunat="server">

<title>Untitled Page</title>

</head>

<body>

<formid="form1"runat="server">

<div>

<asp:textboxID="Textbox1"runat="server"Text="<%# GetValue() %>"></asp:textbox>

</div>

</form>

</body>

</html>

Default2.aspx.cs

using System;

using System.Data;

using System.Configuration;

using System.Collections;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

publicpartialclassDefault2 : System.Web.UI.Page

{

privatestring txtValue;protectedstring GetValue()

{

return txtValue;

}

protectedvoid Page_Load(object sender,EventArgs e)

{

txtValue ="Zeeshan";

}

}

Please check it.

It still does not show the text.


sorry guys its as simple as this

in your code behind you have this

publicpartialclasscodedisplay : System.Web.UI.Page

{

privatestring txtValue ="Zeeshan";protectedvoid Page_Load(object sender,EventArgs e)

{

TextBox1.Text = txtValue;

}

}

and in your aspx you have this

<asp:TextBoxID="TextBox1"runat="server"/>

with all form and html elements.

Good luck


You can do it in your code behind instead of in your markup:

protectedvoid Page_Load(object sender,EventArgs e)

{

if (!IsPostBack)

TextBox1.Text = GetValueStr();

}

privatestring txtValue ="test";protectedstring GetValueStr()

{

return txtValue;

}


But If I want to do it on Mark up then.


Well if you want to do it on mark up then, put it straight in

text="Zeeshan"

text is a property and hence

Don't use code blocks in ASPNET. Avoid if you can avoid it because they are written for backward compatability; instead write an event handler or startup routine in the codebehind which populates the property on the control as necessary.

For example, you could do it in Page_Load - but be sure to surround it with if (! PostBack) so that the value doesn't get overwritten when posting back.

In late binding controls i.e. say a textbox in a gridview etc, you can databind but that again uses reflection etc and hence is slow.


Hi,

If you have to do it in the markup use single quotes instead Text='<%=MyPublicVariable %>'

HTH

Passing variable to another page

This is my first post on these forums so I apologise if it's a common problem. I'm fairly new to ASP.NET.

The situation is as follows:

On one web page, I have created some textboxes where users can search for records in a db (SQL Sever 2005 Beta). The results of their search are then displayed in a datagrid.

The datagrid also has two 'hyperlink' columns which the user can click to be redirected to other pages where related data is displayed. I use the 'URL format string' property of the hyperlink column to display the correct record by using the following string: NameOfForm.aspx?patid={0}. All of this works fine.

One of the hyperlink columns takes the user to a second aspx page which contains a datagrid and shows the many records related to the record the user originally searched for. This second datagrid also has two 'hyperlink' columns, 'Add' and 'Edit'.

These do pretty much as they say. 'Add' allows the user to add a record to the many end of a database relationship, and 'Edit' displays the specific record selected for editing\viewing. Once again all works well so far.

The problem comes when the datagrid on the second web form is empty (i.e. there are no records in the related table in the db) and the hyperlink columns are not visible. I thought I'd get around this by adding a 'Hyperlink' control to my web form. This redirects the user to a web form where a related record can then be added.

This also works but I what I need is the correct 'patid' to be passed onto this page, which is required as the foreign key of the relationship. How can I pass this variable to the next page?

I hope I've described the problem clearly enough.

TIA,

MoYou can pass the patid in the same way you did in the URL before (NameOfForm.aspx?patid={0}).

You can populate it from Request.QueryString["patid"] - which will grab the value you passed before.

Hope that makes sense.

DJ
You can pass the patid in the same way you did in the URL before (NameOfForm.aspx?patid={0}).

You can populate it from Request.QueryString["patid"] - which will grab the value you passed before.

Hope that makes sense.

DJ

Thanks for the reply DJ.

I have already used Request.QueryString ("patid") on the target page. This works fine when the 'sending' page has records to display. When there are no records in the datagrid, the 'patid' does not get passed on. The url field in the target page reads 'http://localhost/Ertocs/AddCancers.aspx?patid={0}' which is not what I'm expecting.

I've set the 'Navigate URL' property of the hyperlink control to 'AddCancers.aspx?patid={0}'. Is this correct or am I missing something simple? Thanks again for your help.

I must be doinf something wrong
I presume you are using Response.Redirect to get to the target page.

Use:

Response.Redirect(String.Format("AddCancers.aspx?patid={0}", Request.QueryString["patid"]));

You are not specifying what needs to be placed at the 0 index.

HTH

DJ
I presume you are using Response.Redirect to get to the target page.

Use:

Response.Redirect(String.Format("AddCancers.aspx?patid={0}", Request.QueryString["patid"]));

You are not specifying what needs to be placed at the 0 index.

HTH

DJ

Thanks for the help DJ. In the end I changed the hyperlink control to a link button with this code:

Server.Transfer("AddCancers.aspx")

with Request.Querystring("patid") in the target page and it works!
Check if the datatable/dataset is Nothing, and if that condition is true, set the visibility of your hyperlink control to true.

passing variable to open a new window

I am new to asp.net. I am wondering how I can open a new window from a button or link. I need to pass a value so both windows are linked. I will appreciate any help, code vb.net

The main page has a label is that stores the ID number, I need to pass this value so I can display in the new window information about this id. Please help. Thanks.

use the Querystring to pass variables to other pages

ie.


Response.Redirect("www.myplace.com/mynewpage.aspx?someValue=399393","_blank");

check this out

http://www.codeproject.com/aspnet/QueryString.asp

hth,

mcm


how about javascript?

<asp:button onclientClick='window.open(.....);' Text='Open New Window' runat=server />


Thanks for the answer. However, I need to open a new window. Could you please help me out? I am using vb.net. Thanks.

javascript DOES open a new window.

read about it. -->http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

mcm


You can test the below code in page_load event which will open a new window using javascript

Page.ClientScript.RegisterStartupScript(me.GetType(),"open","window.open('WebForm2.aspx?id=123','','height=400,width=300');",true)

Where WebForm2.aspx is the name of the window you would like to open. Now in webform2 you can get the value of id using

Dim id as String = Request.QueryString("id")

HC


Yes. But I need to pass from the current window, a value which is saved in a label, to the new window. Thanks for the answer.

dim yourPassInVar as string

Page.ClientScript.RegisterStartupScript(me.GetType(),"open","window.open('WebForm2.aspx?id='" + yourPassInVar + ",'','height=400,width=300');",true)

How about this?



In the current window page_load event use the below code if you want the window to open direclty when the page is being loaded

Page.ClientScript.RegisterStartupScript(me.GetType(),"open","window.open('WebForm2.aspx?id=' + '"+Label1.Text+"','','height=400,width=300');",true)

If you want for example to open it on button click event use the below code

Button1.Attributes.Add("onclick","window.open('WebForm2.aspx?id=' + '"+Label1.Text+"','','height=400,width=300');")

Where Button1 is the button you want to open the window when being clicked

HC


Thanks. How can I do it with a button? When clicking on the button, the variable that holds the id value let's say 123 will be passed to webform2.aspx. Again, thanks for the help.

Great. Thank you for all the help!

;-)

passing variable to new page with LinkButton

I need to pass a variable from a master page to a details page when a user clicks on a link in a DataList. Right now I have a link button, but I don't know how to put the variable into the link at runtime. Hopefully this is just a matter of syntax? How can I make this work?

<asp:DataListID="DataList1"runat="server"DataSourceID="SqlDataSource1">

<ItemTemplate><asp:LinkButtonID="NameLinkButton"runat="server"Text='<%# Eval("Name") %>'PostBackUrl="details.aspx?sponsorID={0}"Font-Bold="true"></asp:LinkButton>

...

</ItemTemplate></asp:DataList>

try this tutorial

Tuorial #4 Understanding Web Application State in the begnner section ofhttp://www.asp.net/learn/videos/default.aspx?tabid=63#howdoi

helped me out alot on understanding how to pass from one page to the other.

Ragscoon =<^_^>=


could you define a string variable and set it equal to the text property of your linkbutton (I'm assuming the text property will be the data item you want to pass to your other page). Then add that string variable to the querystring that will be passed to your other page.

I had to do something like you are doing, except it was a linkbutton in a gridview. It came out like this:

sLocationCode = grdLocationCode.DataKeys(iIndex).Item("ALCODE").ToString()
sCountryCode = grdLocationCode.DataKeys(iIndex).Item("ALCCODE").ToString()
Response.Redirect("LocationCodeDetail.aspx?" & sCountryCode & ";" & sLocationCode)

I believe this addresses your question.


Thanks for the responses. What I am asking is: what is the syntax for concatenating the destination URL with the variable that I want to pass (the sponsorID)?

If I use:

<

asp:HyperLinkID="NameLabel"runat="server"Text='<%# Eval("Sponsor") %>'NavigateUrl='myDetails.aspx?sponsorID=<%# Eval("SponsorID") %>'Font-Bold="true"></asp:HyperLink>

I get:

http://localhost:2097/myFolder/myDetails.aspx?sponsorID=<%#%20Eval("SponsorID")%20%>

It does not parse the SponsorID variable.


To clarify the last line in my previous message:

I get:

http://localhost:2097/myFolder/myDetails.aspx?sponsorID=<%#%20Eval("SponsorID")%20%>It does not parse the SponsorID variable.

Passing Variable to new Page

How do I pass a string to a new page.

For example I want to have a person enter their name and hit submit.
After hiting submit, the name is entered into a database and a confirmation page with the person's name is dislayed.

How do I do this?The simplest way, is with a querystring - -

response.redirect ("newpage.aspx?name=" & txtName.text)

Then, in the new page, just capture the querystring:

Dim sName as string
sName=request.querystring

From there, you can use the variable 'sName' anywhere you'd like on the page, as long as it's dimmed globally to the page (outside any events)
If u want the variable to be used only in one page Querystring is the best choice.If u want to hold the value for many pages, use Sessions.
Thanks,
Kumar.
Thanks. It's perfect.
Okay...I'm dumb..where do I declare the variable Dim strName?
I'm using Webmatrix. Do I delare them in the at the to of the html code or from the code section?

eg.<%declare here%>
in the code section...


Dim strName as string = Request.QueryString("Vari1")


HTH

Passing Variable to UserControl From Parent Page

Hi All, I would like to know how to pass a variable to a user control.

An example would be _menu.ascx, which is a user control and is used in every aspx page such as default.aspx. It's properly set using the @dotnet.itags.org.Register tag in the html pages.

CODEBEHIND FOR DEFAULT.ASPX.CS
--------------
public class _default : System.Web.UI.Page
{
````public string strVariable; // want to use this variable in usercontrol

````private void Page_Load(object sender, System.EventArgs e)
````{
````````strVariable = "Hello World";
````}
}

CODEBEHIND FOR _MENU.ASCX.CS
--------------
public abstract class __menu : System.Web.UI.UserControl
{
````protected System.Web.UI.WebControls.Repeater repMenu;

````private void Page_Load(object sender, System.EventArgs e)
````{
````````DataAccess hdlData = new DataAccess();
````````repMenu.DataSource = hdlData.getMenu(??????); // stuck here!!
````````repMenu.DataBind();
````}
}use a Session["name"] object

psi
Is there another way of passing it, instead of using a Session["name"] variable? My variable is actually in the base class (business class), which all the aspx pages inherit from

CODEBEHIND FOR BUSINESS CLASS PAGEHELPER.CS
--------------------
public class PageHelper : System.Web.UI.Page
{
````public string strVariable; // want to use this variable in usercontrol

````public PageHelper()
````{
````````strVariable = "Hello World";
````}
}

CODEBEHIND FOR DEFAULT.ASPX.CS
--------------
public class _default : PageHelper
{
````private void Page_Load(object sender, System.EventArgs e)
````{
````````// this page inherits the PageHelper.cs class, which
````````// sets all the necessary variables.
````}
}

CODEBEHIND FOR _MENU.ASCX.CS
--------------
public abstract class __menu : System.Web.UI.UserControl
{
````protected System.Web.UI.WebControls.Repeater repMenu;

````private void Page_Load(object sender, System.EventArgs e)
````{
````````DataAccess hdlData = new DataAccess();
````````// this needs to get variable in PageHelper.cs class
````````repMenu.DataSource = hdlData.getMenu(??????); // stuck here!!
````````repMenu.DataBind();
````}
}
yes, you should be able to do this, and assess it from the user control:

PageHelper class is public
public string strVariable;

add this property ...
public string StrVariable
{
get{return var;}
set{var = value;}
}

you would then have to instatiate an instance of PageHelper and call the Property:
PageHelper ph = new PageHelper();

//get variable ...
ph.StrVariable

hope that helped
psi
Thank you for all the help psinyc!!!

It works now =)
good

passing variable to the Parameter value of ObjectDataSource1?

How do I go about passing the value strUserId to the parameter value of ObjectDataSource1?

// get userid for logged in client
if (User.Identity.IsAuthenticated)
{
strUserId = Membership.GetUser().ProviderUserKey.ToString();
}

In the Configure Data Source wizard it is asking for a Parameter Source in the drop down. And the variable strUserId (in the code-behind for the page) is not an option.

How do I make it one?

hi

you need to set the parameter value in Selecting event of the object datasource :

protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e) {this.ObjectDataSource1.SelectParameters[0].DefaultValue = Membership.GetUser().ProviderUserKey(); }


Try setting your Parameter in the ObjectDataSource.Selecting event like so:

protected void ObjectDataSource1_Selecting(object sender, ObjectDataSourceSelectingEventArgs e){e.InputParameters["UserID"] = Membership.GetUser().ProviderUserKey;}

Thank you Anas,

I double clicked the ObjectDataSource1 in design view and was able to get it started.

I will review your code.

Thanks again.

Update: I actually got the 2nd answer in this thread to work.

Passing variable to SQL string is not working.

Hi folks,
The problem I have is that a query string works if hard-coded but
if I pass a variable to it, it does not work as shown here.
This works:
querystring="SELECT * FROM USERS WHERE CNAME = 'MICROSOFT'"
This does not work:
Dim var as string
var = "Microsoft"
querystring="SELECT * FROM USERS WHERE CNAME = " & 'var'"
I have 2 DropDownList controls.
The first control is populated with a dataset of company names.
The second control is populated with a dataset of contact names for
the company that was selected in the first control.
The first control has an OnSelectedIndexChanged event handler.
The first control has a datasource set equal to a function named
GetCompanyNames.
The second control has a datasource set equal to a function named
GetContactNames.
In the OnSelectedIndexChanged event handler, I call the GetContactNames
function to
populate the second control with Contact Names that are associated with the
Company
Name selected in the first control.
All is working well, but the Contact Names in the second control do not
change as
different companies are selected in the first control.
What follows is a pseudo code description of my code:
' THESE ARE CALLED AS GLOBAL VARIABLES AT TOP OF THE PAGE
Dim coName as string
Dim dsCompanyNames as DataSet = New DataSet ( )
Dim dsContacts as DataSet = New DataSet ()
' THIS IS MY OnSelectedIndexChanged EVENT HANDLER
Sub ddlTo_SelectedIndexChanged(sender As Object, e As EventArgs)
Dim list As DropDownList = CType(sender, DropDownList)
coName=list.SelectedItem.Text
GetContactsFromCompanyForThisProject ()
End Sub
' THIS IS MY GETCOMPANYNAMES FUNCTION
Function GetCompanyNamesForThisProject() as DataSet
dsCompanyNames.Clear()
Dim strConnString As String = "JET OLEDB PROVIDER AND MDB FILE"
Dim queryString As String = "SELECT COMPANYNAMES FROM USERS WHERE
PROJECT = @dotnet.itags.org.PROJECT"
Dim dataAdapter As New OleDbDataAdapter (querystring, strConnString)
dataAdapter.Fill(dsCompanyNames, "users")
Return dsCompanyNames
End Function
' THIS IS MY GETCONTACTNAMES FUNCTION
Function GetContactsFromCompanyForThisProject () As DataSet
dsContacts.Clear()
Dim strConnString As String = "JET OLEDB PROVIDER AND PATH TO MDB FILE"
Response.Write("coName = " & coName)
Dim queryString As String
queryString = "SELECT [users].[name] FROM [users] WHERE
(([users].[cname] = '" & coName & "')" & " AND ([users].[project] = '" &
Session("project") & "'))"
' queryString = "SELECT [users].[name] FROM [users] WHERE
(([users]. [cname] = 'FDM') AND ([users].[project] = '" &
Session("project") & "'))"
Dim dataAdapter As New OleDbDataAdapter (querystring,
strConnString)
dataAdapter.Fill(dsContacts, "users")
Return dsContacts
End Function
In the GetContactsFromCompanyForThisProject function, I am able to hard code
a company name and successfully populate the second control but if I attempt
to pass the variable coName to the query string, it will not switch the
contact names for each company that is selected in the first control.
The controls are called out as follows:
<asp:DropDownList
id="ddlTo"
runat="server"
DataValueField="cname"
AutoPostBack="True"
DataSource='<%# GetCompanyNamesForThisProject() %>'
OnSelectedIndexChanged="ddlTo_SelectedIndexChanged"
/>
<asp:DropDownList
id="ddlContact"
runat="server"
DataValueField="name"
AutoPostBack="True"
DataSource='<%# GetContactsFromCompanyForThisProject() %>'
/>
Any replies would be extremely appreciated.Shouldn't it be'
querystring="SELECT * FROM USERS WHERE CNAME = '" & var & "'"
"glenn" <glenn@.discussions.microsoft.com> wrote in message
news:011A49D5-7D96-46B3-A953-BDA72CC829E4@.microsoft.com...
> Hi folks,
> The problem I have is that a query string works if hard-coded but
> if I pass a variable to it, it does not work as shown here.
> This works:
> querystring="SELECT * FROM USERS WHERE CNAME = 'MICROSOFT'"
> This does not work:
> Dim var as string
> var = "Microsoft"
> querystring="SELECT * FROM USERS WHERE CNAME = " & 'var'"
> I have 2 DropDownList controls.
> The first control is populated with a dataset of company names.
> The second control is populated with a dataset of contact names for
> the company that was selected in the first control.
> The first control has an OnSelectedIndexChanged event handler.
> The first control has a datasource set equal to a function named
> GetCompanyNames.
> The second control has a datasource set equal to a function named
> GetContactNames.
> In the OnSelectedIndexChanged event handler, I call the GetContactNames
> function to
> populate the second control with Contact Names that are associated with
> the
> Company
> Name selected in the first control.
> All is working well, but the Contact Names in the second control do not
> change as
> different companies are selected in the first control.
> What follows is a pseudo code description of my code:
> ' THESE ARE CALLED AS GLOBAL VARIABLES AT TOP OF THE PAGE
> Dim coName as string
> Dim dsCompanyNames as DataSet = New DataSet ( )
> Dim dsContacts as DataSet = New DataSet ()
> ' THIS IS MY OnSelectedIndexChanged EVENT HANDLER
> Sub ddlTo_SelectedIndexChanged(sender As Object, e As EventArgs)
> Dim list As DropDownList = CType(sender, DropDownList)
> coName=list.SelectedItem.Text
> GetContactsFromCompanyForThisProject ()
> End Sub
> ' THIS IS MY GETCOMPANYNAMES FUNCTION
> Function GetCompanyNamesForThisProject() as DataSet
> dsCompanyNames.Clear()
> Dim strConnString As String = "JET OLEDB PROVIDER AND MDB FILE"
> Dim queryString As String = "SELECT COMPANYNAMES FROM USERS WHERE
> PROJECT = @.PROJECT"
> Dim dataAdapter As New OleDbDataAdapter (querystring, strConnString)
> dataAdapter.Fill(dsCompanyNames, "users")
> Return dsCompanyNames
> End Function
> ' THIS IS MY GETCONTACTNAMES FUNCTION
> Function GetContactsFromCompanyForThisProject () As DataSet
> dsContacts.Clear()
> Dim strConnString As String = "JET OLEDB PROVIDER AND PATH TO MDB
> FILE"
> Response.Write("coName = " & coName)
> Dim queryString As String
> queryString = "SELECT [users].[name] FROM [users] WHERE
> (([users].[cname] = '" & coName & "')" & " AND ([users].[project] = '" &
> Session("project") & "'))"
> ' queryString = "SELECT [users].[name] FROM [users] WHERE
> (([users]. [cname] = 'FDM') AND ([users].[project] = '" &
> Session("project") & "'))"
> Dim dataAdapter As New OleDbDataAdapter (querystring,
> strConnString)
> dataAdapter.Fill(dsContacts, "users")
> Return dsContacts
> End Function
> In the GetContactsFromCompanyForThisProject function, I am able to hard
> code
> a company name and successfully populate the second control but if I
> attempt
> to pass the variable coName to the query string, it will not switch the
> contact names for each company that is selected in the first control.
> The controls are called out as follows:
> <asp:DropDownList
> id="ddlTo"
> runat="server"
> DataValueField="cname"
> AutoPostBack="True"
> DataSource='<%# GetCompanyNamesForThisProject() %>'
> OnSelectedIndexChanged="ddlTo_SelectedIndexChanged"
> />
> <asp:DropDownList
> id="ddlContact"
> runat="server"
> DataValueField="name"
> AutoPostBack="True"
> DataSource='<%# GetContactsFromCompanyForThisProject() %>'
> />
>
> Any replies would be extremely appreciated.
Yes, I am sorry. I wrote my pseudo code incorrectly. Your syntax
is the way my code actually reads if you follow down through my
question.
So, no it seems that it still does not work when a variable is passed.
I think it might be deeper than just the SQL statement so read on
if you can.
Thanks,
glenn
"ShaneFowlkes" wrote:

> Shouldn't it be'
> querystring="SELECT * FROM USERS WHERE CNAME = '" & var & "'"
>
>
> "glenn" <glenn@.discussions.microsoft.com> wrote in message
> news:011A49D5-7D96-46B3-A953-BDA72CC829E4@.microsoft.com...
>
>
Found what seemed to be in err in my SQL statement that passes a variable
but the change still did not work.
Here it is:
queryString = "SELECT [users].[name] FROM [users] WHERE
(([users].[cname] = '" & coName & "') AND ([users].[project] = '" &
Session("project") & "'))"
"glenn" wrote:
> Yes, I am sorry. I wrote my pseudo code incorrectly. Your syntax
> is the way my code actually reads if you follow down through my
> question.
> So, no it seems that it still does not work when a variable is passed.
> I think it might be deeper than just the SQL statement so read on
> if you can.
> Thanks,
> glenn
> "ShaneFowlkes" wrote:
>
It is bad practice to build your SQL queries this way as it leaves you code
vulnerable to SQL injection exploits. You should use parameters in your SQL
stament such as
"SELECT field1, field2, field3 from table1 where field3 = @.ParameterName"
"glenn" wrote:
> Found what seemed to be in err in my SQL statement that passes a variable
> but the change still did not work.
> Here it is:
> queryString = "SELECT [users].[name] FROM [users] WHERE
> (([users].[cname] = '" & coName & "') AND ([users].[project] = '" &
> Session("project") & "'))"
>
> "glenn" wrote:
>
Response.write your sql statement. We have no way of knowing the values of
your variables
Jeff
"glenn" <glenn@.discussions.microsoft.com> wrote in message
news:8F5639CE-660E-457B-A5F0-B01558358014@.microsoft.com...
> Found what seemed to be in err in my SQL statement that passes a variable
> but the change still did not work.
> Here it is:
> queryString = "SELECT [users].[name] FROM [users] WHERE
> (([users].[cname] = '" & coName & "') AND ([users].[project] = '" &
> Session("project") & "'))"
>
> "glenn" wrote:
>