Dynamic ID name in ASP.NET VB.NET - asp.net

I have about 20 asp:labels in my ASP page, all with ID="lbl#", where # ranges from 0 to 22. I want to dynamically change what they say. While I could write
lbl1.Text = "Text goes here"
for all 23 of them, I'd like to know if there is a way to loop through all of them and change their text.
I thought of creating an array with all my labels, and then just do a For Each loop, but I also have to check if the element exists with IsNothing before I change its text, so I got stuck there.
If anyone can help me, I'd really really appreciate it!
Thank you so so much for your help!!

You can dynamically look up controls on the page by using the System.Web.UI.Page.FindControl() method in your Page_Load method:
Dim startIndex As Integer = 0
Dim stopIndex As Integer = 22
For index = startIndex To stopIndex
Dim myLabel As Label = TryCast(FindControl("lbl" + index), Label)
If myLabel Is Nothing Then
Continue For
End If
myLabel.Text = "Text goes here"
Next

Something like this may work, but you would likely need to tweak it (its from memory, so its not exactly 100% syntactically correct)
For Each _ctl as Control In Me.Controls()
If (TypeOf(_ctl) Is Label) = False Then
Continue For
End If
'add additional filter conditions'
DirectCast(_ctl, Label).Text = "Text Goes Here"
Next
You can also do something similar on the client side using jQuery selectors.

Related

If RadioButton.Checked

I need help loading text file in TextBox3.Text with 3 possible options.
1. If there is nothing in TextBox.Text
2. If there is some help text explication to say user what he have to load
3. if correct path then..
I have all good if I choose only from pathn but I need the 3 option.
My code:
If (TextBox3.Text = "Enter the path from your computer to your text file") And (TextBox3.Text = "") And RadioButton1.Checked = True Then
Dim FILE_NAME = Path.Combine(Directory.GetCurrentDirectory(), "\default.txt")
End If
If TextBox3.Text <> "" Then
FILE_NAME = TextBox3.Text
End if
PS: Dim file_name is already declared, but i didnt want to enter here all that codes. Also I tried to not add () and laso looked in MSDN declaration and did exactly same but it wont load nothing, if I dont enter path, OR if I let the explication to user so it wont load default.txt
Thank you
I would like to explain to you what I have been (trying) to explain in the comments (obvoiusly) without much success:
You have written, as your first line:
If (TextBox3.Text = "Enter the path from your computer to your text file") And (TextBox3.Text = "") And RadioButton1.Checked = True
So, YOU are testing (in a shorter way):
IS(TextBox got the value of "Enter the path from your computer to your text file")?
Yes?
Then IS (textBox ALSO the value of "")
Yes?
Then IS (the radio button also checked?)
However, you're code will NEVER REACH the 'is the radiobutton...' part, Since textbox cannot be both
"Enter the path from your computer to your text file" AND "" (nothing/Blank)
I hope you now understand the reason for your code never executing that part of your first if statement.
It's impossible for the code to be true with that condition, and I hope now you will be able to see why.

Vb.net Simple TextBox conversion to integer gives error input string was not in a correct format

I have some text boxes on a form I would like to validate. I want to confirm that they contain only numbers, and that the "total" text box is equal to the sum of the other boxes:
Protected Sub TotalBoxValidator_ServerValidate(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles TotalBoxValidator.ServerValidate
If ((Convert.ToInt32(Box1.Text) + Convert.ToInt32(Box2.Text) + Convert.ToInt32(Box3.Text) + Convert.ToInt32(Box4.Text) + Convert.ToInt32(Box5.Text) + Convert.ToInt32(Box6.Text) + Convert.ToInt32(Box7.Text)) = Convert.ToInt32(TotalBox.Text)) Then
args.IsValid = True
Else
args.IsValid = False
End If
End Sub
Now during testing, I fill out the boxes with only integers. The total box is automatically updated to be the sum of the other boxes. However, when I click my "Submit" button on the form, and all the validators run, this one does not work properly.
The code throws an error on the first if statement, saying that the input to the Convert.ToInt32 calls is invalid. "input string was not in a correct format". I am positive that I am putting integers in each box, and that my TotalBox is equal to the sum of the other boxes. So I'm kind of stuck on why this would throw an error. Perhaps I am doing my conversion from string to integer wrong?
Does anyone have any idea what is going on here?
My issue had to do with the fact that my TotalBox (an ASP.net TextBox control) had its "Enabled" property set to false. I did this because it made the textbox greyed out, and the user could not change the value of the text box. Because the TextBox was not Enabled, I could not access the value of the TextBox at runtime. Though I was successfully changing its value in the page's javascript, and visually the value of the textbox was updating on the page, trying to use its value as a string in the code behind caused the error.
It did not have to do with the logic of the code or any syntax error. To fix this problem, I set the Enabled property of the TotalBox to true. Now the box is no longer greyed out, and user has the ability to change their total to be different than the sum of the boxes, which is not exactly what I want, but then again I am validating the total here so it is not a big deal. I will go back and try to grey out the textbox in javascript instead, because I have a feeling this will maintain the ability to get the TextBoxes value, while still having it be greyed out.
Edit: The above solution did work. For others experiencing this problem, consider trying to grey out the textbox using javascript, instead of any .net or asp code.
Here is the updated code:
Protected Sub TotalBoxValidator_ServerValidate(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles TotalBoxValidator.ServerValidate
Dim Box1Value = Convert.ToInt32(Box1.Text)
Dim Box2Value = Convert.ToInt32(Box2.Text)
Dim Box3Value = Convert.ToInt32(Box3.Text)
Dim Box4Value = Convert.ToInt32(Box4.Text)
Dim Box5Value = Convert.ToInt32(Box5.Text)
Dim Box6Value = Convert.ToInt32(Box6.Text)
Dim Box7Value = Convert.ToInt32(Box7.Text)
Dim TotalBoxValue = Convert.ToInt32(TotalBox.Text)
If (Box1Value + Box2Value + Box3Value + Box4Value + Box5Value + Box6Value + Box7Value = TotalBoxValue) Then
args.IsValid = True
Else
args.IsValid = False
End If
End Sub
Now, here is what was really helpful for debugging this situation. Try putting your conversions on different lines, because then when the program halts, it shows you exactly which conversion is going wrong. In my case, I got an error on the TotalBoxValue line. So I knew that something was going wrong with my TotalBox. What was different with the TotalBox than any of the other text boxes? Well, first of all, it was the total. But I knew this was working correctly. So then I thought about its properties. Its enabled property was set to false, different from the other boxes. So i knew this had to be changed.
For some reason in asp.net, when a control has its Enabled property set to false, you cannot access any of its properties at runtime. This is something I have noticed that is maybe not intuitive.
I suggest you use CompareValidators on your textboxes.
This will assure that the page won't even postback if your values aren't appropriate. Example markup:
<asp:CompareValidator ErrorMessage="errormessage" ControlToValidate="Box1"
runat="server" Type="Integer" />
Then you could technically keep the code you've already posted, though if you wanted to forego the validators something like this would treat invalid input as 0:
Dim temp As Integer
Dim boxTotal = {box1.Text, _
box2.Text, _
box3.Text, _
box4.Text, _
box5.Text, _
box6.Text, _
box7.Text} _
.Select(Function(text) If(Integer.TryParse(text, temp), temp, 0)) _
.Sum()
Integer.TryParse(TotalBox.Text, temp)
args.IsValid = boxTotal = temp
You are attempting to convert a text value to an integer before knowing if the text value is an integer, please read up on
integer.TryParse
dim v1, v2, v3, v4, v5, v6, v7 as integer
if not integer.tryparse(box1.text, v1) then
args.IsValid = False
return
endif
if not integer.tryparse(box2.text, v2) then
args.IsValid = False
return
endif
......

How to change the text of multiple labels using a loop

I am trying to change labels in an asp.net web form. My label IDs are lbl1, lbl2, lb3, etc.
con.Open()
For i = 1 To 6
SQL = "SELECT Question FROM Question WHERE TestID=" & Session("TestID") & " AND QuestionID=" & Convert.ToString(i) & ";"
Dim cmd As New OleDbCommand(SQL, con)
Dim myControl As Control = FindControl("ContentHolder_" & "lbl" & Convert.ToString(i))
myControl.Text() = cmd.ExecuteScalar
Next
con.Close()
This obviously doesn't work as .Text is not a property of myControl.
I couldn't work out how to work around this problem.
p.s. I inspected the element of the label in google chrome and found out that it has ContentHolder_ before the name I gave in the id of the element. This is because I use a masterpage and thats why it is there.
Can anyone help?
Control is a base class of all types of webform controls. You need to use the specific type of control you are using. For example, if it is a <asp:Label> control, you need to use the Label type instead of the Control type. Like this:
Dim myControl As Label = CType(FindControl("ContentHolder_" & "lbl" &
Convert.ToString(i)), Label)
myControl.Text = "whatever"
There is a second thing wrong with your code, however. You are putting your SQL query in a loop. You should always try to reduce the number of round trips to your database. In this case, that means changing your code to query the database once, and then using an OleDbDataReader to read the data back. Your code will perform much faster that way.

Dynamically Adding Multiple User Controls vb.net

I have a User Control which returns a table of data, which in some cases needs to be looped, displaying one on top of another.
I am able to dynamically add a single instance of this by placing a fixed placeholder in the page.
I am now trying to work out how to add more than one, given that I don't know how many might be needed I don't want to hard code the Placeholders.
I've tried the following, but I am just getting one instance, presumably the first is being overwritten by the second
My HTML
<div id="showHere" runt="server"/>
VB
Dim thisPh As New PlaceHolder
thisPh.Controls.Add(showTable)
showHere.Controls.Add(thisPh)
Dim anotherPh As New PlaceHolder
anotherPh .Controls.Add(showTable)
showHere.Controls.Add(anotherPh)
How do I make it add repeated tables within the showHere div?
I would advise generating a different ID for each of your table. For example,
Dim i As Integer
i = 0
For each tbl in ShowTables
tbl.ID = "MyTab" + i.ToString()
i = i + 1
showHere.Controls.Add(tbl)
showHere.Controls.Add(New LiteralControl("<br />"))
Next
On other hand, it would make more sense to have a your user/custom control generate html for a single table and then nest your user/custom control within a repeater (or similar control such as ListView etc).
Did you tried simply, this:
For each tbl in ShowTables
showHere.Controls.Add(tbl)
showHere.Controls.Add(New LiteralControl("<br />"))
Next
After fussing with this issue myself, I stumbled across below solution.
On button click()
LocationDiv.Visible = True
Dim existingItems As New List(Of Object)
If Not Session("existingItems") Is Nothing Then
existingItems = CType(Session("existingItems"), List(Of Object))
For Each item As Object In existingItems
LocationDiv.Controls.Add(item)
Next
existingItems.Clear()
End If
LocationDiv.Controls.Add(New LiteralControl("<b>" & Text & "</b>"))
For Each item As Object In LocationDiv.Controls
existingItems.Add(item)
Next
Session.Add("existingItems", existingItems)

dynamically set control ID

i have few texboxt and dropdownlist, which their id would be something like "txtName1, txtName2, txtName3..." and "ddlAction1, ddlAction2, ddlAction3...."! I would to to dynamically set the textboxt and dropdownlist id into something like this:
for i as integer = 0 to 6
a = txtName+i.text
b = ddlAction+i.SelectedValue
next i
Need help from you guys to do this! thanks....
The key is FindControl, which looks up a control by its expected ID:
For i As Integer = 0 To 5
Dim txt As TextBox = TryCast(Me.Page.FindControl("txtName" & i.ToString()), TextBox)
Dim ddl As DropDownList = TryCast(Me.Page.FindControl("ddlAction" & i.ToString()), DropDownList)
If txt IsNot Nothing AndAlso ddl IsNot Nothing Then
Dim a As String = txt.Text
Dim b As String = ddl.SelectedValue
End If
Next
It will return null/nothing if a control with that ID isn't found.
Note that FindControl will only search the given control's (or Page's) immediate children, not the entire control tree. To search recursively, you need to use your own FindControl method.
Private Function FindControlRecursive(ByVal control As Control, ByVal id As String) As Control
Dim returnControl As Control = control.FindControl(id)
If returnControl Is Nothing Then
For Each child As Control In control.Controls
returnControl = child.FindControlRecursive(id)
If returnControl IsNot Nothing AndAlso returnControl.ID = id Then
Return returnControl
End If
Next
End If
Return returnControl
End Function
.Net requires you to resolve your variable names at compile time, rather than runtime like your code is trying to do. This is a good thing, as it prevents you from making certain kinds of errors. But it does mean you'll need to look at an alternative approach for this particular problem.
One option is a FindControl -based method. But odds are the controls you care about are grouped together on the page. If they aren't already, put them in a common container control, like a panel. Then you can do something like this (requires System.Linq):
For Each t As TextBox In MyContainer.Controls.OfType(Of TextBox)()
a = t.Text
Next t
For Each d As DropDownList In MyContainer.Controls.OfType(Of DropDownList)()
b = d.SelectedValue
Next d
Also, I hope you're really doing something other than assignment inside your loop. Otherwise, most of the work is for nothing as you will exit the loop having simply assigned the value from the last iteration to your variable.
Finally, it seems like these controls might work in pairs. To me, that's a situation that calls out for you to implement a user control.
I'm not a webforms expert, but I believe the page stores a reference to each control present in the page.
You can think of webforms like an n-ary tree... each control has a parent and can have 0 to many children. So, if these are static controls you should just be able to grab a reference to their parent and iterate over that... with no need for the children's ids.
Also, you can query for children based on their id... something like myControl["myID1"] so you can concat the number with the string and get the control that way.
Lastly, if these are purely dynamic controls, i.e. you don't know how many there are, just store references to them in an ordered collection and iterate over them that way.
EDIT:
Here we go:
WebControl myControl;
myControl.Controls.Add(someControlReference);
Then, to grab a control by ID:
WebControl someControl = myControl.FindControl("someControlID1");
From there you can do like:
string a = someControl.Text

Resources