Variable Variables

Hi,

Maybe the solution is very simple, but how do I create variable variables in vb.net? I want to use the value of a variable as a part of the name of another variable. A very simple example below:
code:
Dim a As String
a = "1"
Label a.Text = "hi"

page:
<asp:Label id="Label1" runat="server">Label</asp:Label>

In need this to change a range of values by using just one loop. I can´t do that without creating a variable variable name.
0
tricktracker
3/11/2005 10:11:59 AM
asp.net.getting-started 91979 articles. 4 followers. Follow

5 Replies
1232 Views

Similar Articles

[PageSpeed] 35

Hi,

check out this little demo application I created for you:

<%@ Page Language="VB" %>
<script runat="server">
Sub LinkButton1_Click(sender As Object, e As EventArgs)
For i As Integer = 1 To 3
DirectCast(Page.FindControl("Label" & i.ToString), Label).Text = "Hello, World!"
Next
End Sub
</script>
<html>
<head>
</head>
<body>
<form runat="server">
<p>
<asp:Label id="Label1" runat="server">Label</asp:Label>
</p>
<p>
<asp:Label id="Label2" runat="server">Label</asp:Label>
</p>
<p>
<asp:Label id="Label3" runat="server">Label</asp:Label>
</p>
<p>
<asp:LinkButton id="LinkButton1" onclick="LinkButton1_Click" runat="server">Change text</asp:LinkButton>
</p>
</form>
</body>
</html>

Especially, pay attention to the DirectCast. You have to find the correct control on the page which accepts as input parameter a string. Then you have to cast it to a certain class, in this case to the Label control class. Once it has been casted then you can access its properties. In this demo I set the Text property.
Hope this helps you out.
Grz, Kris.
Read my blog. Handy Firefox plugins for web developers.


Workaround for non working Mark as answer buttons.
0
XIII
3/11/2005 11:33:36 AM
Thanks! It works perfectly! I hope this feature will be supported in a much easier way in future versions of vb.net. Was used to it in php, where it´s already easy (just $$var).
0
tricktracker
3/11/2005 12:35:17 PM
Hi,

it's not vb.net but ASP.NET. You'll also have to cast to the correct type after a FindControl in any other .NET enabled language (like C#).
Grz, Kris.
Read my blog. Handy Firefox plugins for web developers.


Workaround for non working Mark as answer buttons.
0
XIII
3/11/2005 2:51:34 PM
Hi, I'm back again ;)

I used the casting as shown above, it works very well, but now I want to set a variable and not a value of control property.
The new problem is that I want to set a range of html properties by using a loop in the code. Each html property has a vb.net string variable as value. Al those variable names are the same, except the number at the end is different.
In the following example a loop should set each cell color one by one. String selectedcell will contain the name of the cellcolor that gets another color than the rest.
Code:
Sub setcellcolors (selectedcell As String)
For i As Integer = 0 To 2
Dim tmpcell As String
tmpcell = "cellcolor" & i.ToString
If (tmpcell = selectedcell)
>>>"cellcolor" & i.ToString<<< = "#c9dfdb"
Else
>>>"cellcolor" & i.ToString<<< = "#ffffff"
End If
Next
End Sub

Page:
....
<td bgcolor="<%=cellcolor0%>"
</td>
<td bgcolor="<%=cellcolor1%>"
</td>
<td bgcolor="<%=cellcolor2%>"
</td>
....
Ofcourse it doesn´t work, this: >>>"cellcolor" & i.ToString<<< should be replaced by something else. I already searched how to cast a string to a variable name, but didn´t find anything. CType and DirectCast can´t do that if I´m right.
Anyway, the example in this post may not be completely correct, and the solution for this example could also be easier than using variable variables, but I just need to know how I do it this way because I will have to use it in other situations as well.
0
tricktracker
3/11/2005 3:22:25 PM
Still didn´t find out myself how to do this. Can somebody please look at the code in my previous post?

BTW, sorry the code isn´t between code tags, forgot it and couldn´t change it anymore.
0
tricktracker
3/18/2005 9:43:00 AM
Reply:

Similar Artilces:

variable variables?
Hello! How to make a variable receive an increment in the name? I want to do it for example: I have: Label1->Caption = "1"; Label2->Caption = "2"; Label3->Caption = "3"; Label4->Caption = "4"; And I want to do something like that: for (i=1; i<5; i++) { Label+i->Caption = i; } Any idea? Can I do something like that? Thanks and regards Alexandre Create a vector of pointers to the various objects. In your case below, construct a vector (called Labels) of pointers to TLable long enough to hold pointers to...

variable of variables
Say I have 2 scenarios and I want to use a different variable depending on which scenario applies without coding this logic. So I could have a database table t_variables which has: Scenario: Variable: --------- -------- 1 v_name 2 v_company In my Powerbuilder code I'd have values in v_name & v_company. What I'd like to be able to do is to select which variable to use from the table and assign that to something, e.g. select variable into v_variable from t_variables where scenario = 1 so at this point v_variable would be 'v_name'...

variable not a variable
Error:Must declare the variable '@cartDateTime'. 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.Data.SqlClient.SqlException: Must declare the variable '@cartDateTime'. Dim connStr As SqlConnection            Dim cmdInsert As SqlCommand            Dim strInsert As String      &n...

Javascript variable to VB.Net Variable
Could someone please point me to a way to pass a string that is contained in a Javascript variable over to a Visual Basic.Net variable? If something already exists in the Forums I could not find it through the search. Thanks in advance, Welcome to the ASP.NET Forums, Haywire. The following article shows how you can pass Javascript information back to your server-side code: How postbacks work in ASP.NETAlister...

getting the exported variable into a perl variable
------=_Part_110760_21946666.1155278901075 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline Hi, I got a program which will access a exported variable in the shell. Can anyone help me with this? ------=_Part_110760_21946666.1155278901075-- Perl maintains environment variables in a special hash named %ENV Krishnakumar K.P Sr.Software Engineer Cybage Software Pvt. Ltd (An SEI-CMMI Level 5 Company) West Avenue, Kalyani Nagar Pune - 411 006 Tel: 020- 66041700/ 66044700 extn: 3178 Email: krishnakumarp@cyb...

How to get a URL variable and set it to a local variable
Very easy question I presume. Does anyone know the answer to get a URL variable and set it to a local variable ? Thanks dim myvar as string = Request.QueryString("someURLvar")Mike Banavige~~~~~~~~~~~~Need a site code sample in a different language? Try converting it with: http://converter.telerik.com/...

How to get session variable value into a static variable
Hi, On page preinit i am adding few session variables. Now i want to retrive these session variable values into my static variables. protected void Page_PreInit(object sender, EventArgs e) {Session.Add("T", "Default"); Session.Add("T1", "Red"); Session.Add("T2", "Blue");   }   i have few static variables which shud contain these vaules.  public string TT; public string TT1; public string TextForeColor =sess = "#FFFFFF";   i want to get T value into TT ... T1 into TT1..and so on &n...

centralized variable variables
Hi, Hi, I want to set pathnames in a centralised module (called with use or require). Is it possible to send an variable (through the env or as an argument, or ....) so I can use the variable $dir from the module test.pl to set the variable $vardir in param.pl. ?? Any help greatly appreciated. Bernard -----------cat test.pl #!/usr/bin/perl #use strict; my $dir = $ARGV[0]; require "param.pl"; print("path1 $path1\n"); print("path2 $path2\n"); # ---------cat param.pl #!/usr/bin/perl my $basepath = "/var/tmp"; my $vardir =...

Variable within a variable?
I have a lot of text boxes that I need to get into an array.  Say they are called txt1 - txt80.  Is it possible to use an index variable to go through each text box?  Something like this txt"index" <---obviously not correct, but is there something out there like this?Thank you for any help You can iterate through your page controls and put them into the array if they are of type TextBox.. foreach(Control wc in Page.Form.Controls) { if (wc.GetType().Name == "TextBox") { //add the control to the array } }Kumar Reddi Works well, thanks for your help!...

been a while
I haven't coded in perl for far too long... that aside.. How do I define variable variable names ? I have an array that contains the header cells of some long columns, from which i want to create new arrays which are called by the names in the array. e.g. @header = (Name, Address, Date, Expiry) And create arrays @name, @address...etc Header contents, of course, change order and content. Hope you can help Michael Carmody MDU, Public Health Lab Dept. of Microbiology and Immunology The University of Melbourne, Parkville On Thursday, May 23, 2002, at 05:39 , ...

Assigning a Variable with other Variables.
I have a real quick noob question. I have the following variables. First_Name = Server.HtmlEncode(txtFirstName.Text) Last_Name = Server.HTMLEncode(txtLastName.Text) I want to assign these two variables to another along with some other information so it looks like tte/john.doe I have this, but I am obvisouly doing it wrong. Thanks for any help. UserID = "tte/"First_Name"."Last_Name Let me guess: you came from PHP. Try UserID = string.Format("tte/{0}.{1}", First_Name, Last_Name) or UserID = "tte/" &am...

Variable variable names
------_=_NextPart_001_01CB7729.624A48CF Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Hello, In the below code I am desperately trying to accomplish the valid use of = variable variable names but still fail. I have already read many sites, = tutorials, mailing list posts, all saying that this is best accomplished = by using a hash. Please would you tell me if I understood that correctly = and, even more important, if I interpreted and tried to realize it = correctly? And if someone could tell me why the script gives me error...

variable variable-names
Hi all, I'm trying to write a script that will pull out values for form data radio buttons for muliple answers. This is what a standard line looks like: <INPUT TYPE="radio" NAME="answer1" VALUE="blah">Blah For each question I've tried to make up a separate set of arrays containing the button values: open (QUES, "<questions.poll"); foreach $line (<QUES>) { chomp $line; if ($line =~ m|[^"]*NAME="answer(\d)"\s*VALUE="([^"]*)"|) { $num = $1; $value_label = $2; ...

my $variable verse $variable
Greetings, Being new to perl can someone explain why my is in form of variables and what is the purpose? Thanks TMC wrote: > Greetings, > Being new to perl can someone explain why my is in form of variables > and what is the purpose? 'my' is used to declare a variable and limit its scope. If you `use strict;` (and you should) you must declare all unqualified variables. #!/usr/bin/perl use strict; use warnings; my $a = 'a'; { my $a = 'b'; print "$a\n"; } print "$a\n"; __END__ See: perldoc -f m...

Web resources about - Variable Variables - asp.net.getting-started

Variable - Wikipedia, the free encyclopedia
Text is available under the Creative Commons Attribution-ShareAlike License ;additional terms may apply. By using this site, you agree to the ...

Westpac interest rate rise is one of many variable loan rate rises
WESTPAC is not alone in hitting its owner-occupier customers with a surprise interest rate rise, as dozens of other variable rate home loans ...

Airbnb upgrades variable pricing tool for hosts
Online home rental group Airbnb is rolling out an upgraded variable pricing tool that automatically raises or cuts room rates based on supply ...

Commonwealth Bank raises variable home loan rates
Home owners' mortgage costs are set to rise by hundreds of dollars a year, after the Commonwealth Bank became the latest bank to hike interest ...

CBA lifts variable home loan rates to offset costs associated with stricter capital requirements
The Commonwealth Bank to lift its home loan interest rates independently of the Reserve Bank to partially offset costs associated with stricter ...

Washington Square Signs Spielbergs, Choi Joins Variable and More
... films and an episode of the HBO comedy series "Girls," on which he plays the role of Ray Ploshansky. New York-based creative collective Variable ...

YouTube v10.32 Tweaks Some Interface Elements And Includes Hints About Virtual Reality Content And Variable ...
Forget Update Wednesday! Monday is the new big day. Not only were we treated to the latest M preview release and the official Marshmallow name, ...

"You have to ignore many variables to think women are paid less than men. California is happy to try." ...
Writes Sarah Ketterer in The Wall Street Journal in "The ‘Wage Gap’ Myth That Won’t Die" (which you can get to without subscribing if you Google ...

Expert Reveals the Latest Variable Capacity Technology
Learn about gForce Ultra CRAC equipment, the latest variable capacity technology to lower energy usage and increase reliability.

AD/CVD ruling and overseas capacity expansions are variables to the current PV boom, says EnergyTrend ...
China's National Reform and Development Commission has announced that there will be no significant reduction in feed-in tariff (FiT) rates for ...

Resources last updated: 12/28/2015 7:29:31 AM