Cast a string to a name of a web label - asp.net

HI, using vs2008 and building a web app. On a asp page called blackjack.aspx, I have four labels with id of lbBJTStatusP1 lbBJTStatusP2 lbBJTStatusP3 lbBJTStatusP4.
I want to address those labels in a single sub by casting the casting two strings into the control name, so that string lbBJTStatusP & "1" would refer to lbBJTStatusP1.This is done on the code behind page.
So far I have tried this but with no success. boxct refers to either "1" "2" "3" or "4".
DirectCast(blackjack.Controls.Find("lbBJTStatusP" & boxct, True)(0), Label).BackColor = stoodcolor
Can it be done and if so how. Thanks for all and any help.

You can't "cast" a string to a specific instance of a control.
What you can do is use FindControl: that accepts a string, searches (one level deep, not more) for a control with that name and returns it. The method returns a Control, so you might need to cast it to Label.

I have labels named lblqu01ex - lblqu10ex. I set the text value through coding as follows.
for i = 1 to 10
ex = "lbl" & IIf(i = 10, "qu10", "qu0" & i) & "ex"
DirectCast(FindControl(ex), Label).Text = 2*100/i
next
Its work.

Related

How to remove duplicates in a listbox VB.net

I am trying to remove duplicates in a ListBox which is populated by a query pull. I use this code to prevent adding duplicates in VB 6.0 but does not work when converted over to VB.net. Is there a substitute method to prevent or remove duplicates.
colSchema = dr("Col_Schema").ToString
If Not lstSchema.Items.ToString.Contains(colSchema) Then
lstSchema.Items.Add(New ListItem(colSchema))
End If
try
colSchema = dr("Col_Schema").ToString
dim exists as boolean = false
for i as integer = 0 to lstSchema.items.count - 1
if lstSchema.items.item(i) = colSchema then
exists = true
end if
next
if exists = false then
lstSchema.Items.Add(New ListItem(colSchema))
end if
This code
lstSchema.Items.ToString
is converting Items to a string. Items is most likely the type ListBox.ObjectCollection (if this is WinForms) or a similar collection type for other UI frameworks. Calling ToString on such classes will end up calling Object.ToString, which just returns the name of the class.
Instead, try
lstSchema.Items.Contains(colSchema)
If that does not work for some reason, please update your question explaining exactly what you were trying to solve by calling ToString.

Looping through different dropdown lists

I have multiple controls on a page that are all similar and are all numbered. For instance, I have multiple month controls like this:
Replacement1MonthDropDownList
Replacement2MonthDropDownList
Replacement3MonthDropDownList
Etc.
But when I have common code that works on all of the controls, I need a big Select Case statement like this:
Select Case Count
Case 1
Call Me.FillReplacements(rf.Replacements(0), Me.Replacement1MonthDropDownList, Me.Replacement1AmountTextBox, Me.ReplacementSaveButton)
Case 2
Call Me.FillReplacements(rf.Replacements(0), Me.Replacement1MonthDropDownList, Me.Replacement1AmountTextBox, Me.ReplacementSaveButton)
Call Me.FillReplacements(rf.Replacements(1), Me.Replacement2MonthDropDownList, Me.Replacement2AmountTextBox, Me.SplitButton1)
Is it possible to loop through the controls and get them by name--justreplacing the numbers in the name with the current Count in my loop?
Sorry, I'm very new to Visual Basic! :S
Yes, you can. The Page class (Me, in this case) has a FindControl method which allows you to find a control by name. So, for instance, you could do something like this:
Dim monthControl As Control = Me.FindControl("Replacement" & Count.ToString() & "MonthDropDownList")
Dim splitControl As Control = Me.FindControl("SplitButton" & Count.ToString())
If you need to cast them as a more specific type, you could use DirectCast. For instance:
Dim monthControl As DropDownList = DirectCast(Me.FindControl("Replacement" & Count.ToString() & "MonthDropDownList"), DropDownList)
Alternatively, and perhaps preferably, you could make an array of controls so you could access them by index. For instance, if you had an array like this defined:
Private monthControls() As DropDownList = {Replacement1MonthDropDownList, Replacement2MonthDropDownList, Replacement3MonthDropDownList}
Then you could access it by index like this:
Dim currentMonthControl As DropDownList = monthControls(Count)

Save an aspx page in session

I have a login page that return the userName to a page called User.aspx. The User.aspx shows the information about the user based on a sql select. I fill 12 labels on the page with the result of the select. I want to keep the information of my 12 labels if the user Quits and enter again in the page.
I save my session
Session("UserPage") = (litHello.Text And litAddresse.Text And litAnimalGenre.Text And litCouriel.Text And litNomAnimal.Text And litPays.Text And litPostalCode.Text And litProvince.Text And litRace.Text And litTel.Text And litVille.Text)
Now how I can proceed too fill all my label with my saved session call UserPage??? That is the question !!! The code is VB.NET
Thank's for helping me
Answer on your question:
I would make a class with multiple properties and save that in the session ;)
Eg.
Public class PropertySession
Public Property ID as integer
Public Property Name as String
Public Property Address as String
End Class
Then (the long way)
Dim currentPropertySession as PropertySession
With PropertySession
.ID = litID.Text
.Name = litName.Text
.Address = litAddress.Text
End With
And finally store
Session("Property") = currentPropertySession
or the shorter way (still need to declare PropertySession)
Session("Property") = New PropertySession With { .ID = litID.Text, .Name = litName.Text, .Address = litAddress.Text}
You can even do this - only to be complete, but i wouldn't do this if i were you -
Session("Property") = New Object With { .ID = litID.Text, .Name = litName.Text, .Address = litAddress.Text}
Additional
There are 8 ways to store data of a user to the next page.
Check out which one is good enough for you.
You can continue to do it the way you have it and then when you read out the session split the values into an array and then loop through your array. You will need to use a delimiter to separate the values so you can split them.
Session("UserPage") = (litHello.Text & "|" & litAddresse.Text & "|" & litAnimalGenre.Text & "|" & litCouriel.Text & "|" & litNomAnimal.Text & "|" & litPays.Text & "|" & litPostalCode.Text & "|" & litProvince.Text & "|" & litRace.Text & "|" & litTel.Text & "|" & litVille.Text)
The when you read out the the values:
dim userInfo as string() = Session("UserPage").toString().split("|")
Now set your labels accordingly
label1.text = userInfo(0)
label2.text = userInfo(1)
etc...
The one problem here is you have to be sure all your values in the session have a value and if they don't you fill it with an empty string "" so that your split will populate the correct number of values.
For authentication things you can use out of the box functionality from ASP.Net. It offers an API with standard providers like SQL Membership Provider etc.
By using web.config settings, you can allow users to access only certain portions of your site (like a members area). Then, if you like to query more information than the Membership Provider API allows you to, you can get the authenticated user identity (you natural key) from anywhere like:
Page.User.Identity.Name
With this information, you can query your database.

Object Data Source

I'm creating a gridview using an objectdatasource and it works fine when pulling all records. But when I want to use the selectCountMethod the grid shows no values.
I Step through the code and my getInvoices (gets the requested data) returns data and the getInvoicesCount (gets the total record count). But then when I go through the rowdatabound of the gridview there's nothing in there and no data displays.
Here is my code to set the objectdatasource. Any reasons why it wouldn't work or something special that needs to be done for getting the selectcount to work?
Me.ODS.TypeName = "invoice"
Me.ODS.EnablePaging = True
Me.ODS.SelectMethod = "getInvoices"
Me.ODS.SelectCountMethod = "GetInvoiceCount"
Me.ODS.StartRowIndexParameterName = "startRowIndex"
Me.ODS.MaximumRowsParameterName = "maximumRows"
Me.ODS.SelectParameters.Add("strbu", strBusUnit)
Me.ODS.SelectParameters.Add("stremailAddress", emailAddress)
Me.ODS.SelectParameters.Add("startDate", search_startdate)
Me.ODS.SelectParameters.Add("enddate", search_enddate)
Me.ODS.SelectParameters.Add("sortExpression", sortExpression & " " & sortDirection)
With gvInvoices
.PageIndex = intPageIndex
.PageSize = 25
.DataBind()
End With
Check if the count being returned is an integer . debug it . maybe it is null.
and if not null parse it to an integer
I was able to figure this one out. The count was being returned as a long instead of integer. I changed it to integer and all is working great

How do I traverse a collection in classic ASP?

I want to be able to do:
For Each thing In things
End For
CLASSIC ASP - NOT .NET!
Something like this?
dim cars(2),x
cars(0)="Volvo"
cars(1)="Saab"
cars(2)="BMW"
For Each x in cars
response.write(x & "<br />")
Next
See www.w3schools.com.
If you want to associate keys and values use a dictionary object instead:
Dim objDictionary
Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.Add "Name", "Scott"
objDictionary.Add "Age", "20"
if objDictionary.Exists("Name") then
' Do something
else
' Do something else
end if
Whatever your [things] are need to be written outside of VBScript.
In VB6, you can write a Custom Collection class, then you'll need to compile to an ActiveX DLL and register it on your webserver to access it.
The closest you are going to get is using a Dictionary (as mentioned by Pacifika)
Dim objDictionary
Set objDictionary = CreateObject("Scripting.Dictionary")
objDictionary.CompareMode = vbTextCompare 'makes the keys case insensitive'
objDictionary.Add "Name", "Scott"
objDictionary.Add "Age", "20"
But I loop through my dictionaries like a collection
For Each Entry In objDictionary
Response.write objDictionary(Entry) & "<br />"
Next
You can loop through the entire dictionary this way writing out the values which would look like this:
Scott
20
You can also do this
For Each Entry In objDictionary
Response.write Entry & ": " & objDictionary(Entry) & "<br />"
Next
Which would produce
Name: Scott
Age: 20
One approach I've used before is to use a property of the collection that returns an array, which can be iterated over.
Class MyCollection
Public Property Get Items
Items = ReturnItemsAsAnArray()
End Property
...
End Class
Iterate like:
Set things = New MyCollection
For Each thing in things.Items
...
Next
As Brett said, its better to use a vb component to create collections. Dictionary objects are not very commonly used in ASP unless for specific need based applications.
Be VERY carefully on using VB Script Dictionary Object!
Just discover this "autovivication" thing, native on this object: http://en.wikipedia.org/wiki/Autovivification
So, when you need to compare values, NEVER use a boolen comparison like:
If objDic.Item("varName") <> "" Then...
This will automatically add the key "varName" to the dictionary (if it doesn't exist, with an empty value) , in order to carry on evaluating the boolean expression.
If needed, use instead If objDic.Exists("varName").
Just spend a few days knocking walls, with this Microsoft "feature"...
vbscript-dictionary-object-creating-a-key-which-never-existed-but-present-in-another-object

Resources