Referencing a label in my asp.net page from code behind - asp.net

Using VS 2013 VB.
I have the following line of code
Dim myLabel As Label = CType(Me.Controls("lbladd"), Label)
Whenever I run the page I get the following error
Conversion from string to type integer is not valid
I have several labels on my asp.net page each with a number at the end of the id which increases by one. My eventual aim is to loop through each label and add a string to each one using something like the following
For i = 0 To splitAddress.Count - 1
Dim myLabel As Label = CType(Me.Controls("lbladdress" & i + 1), Label)
myLabel.Text = splitAddress(i)
Next
Where splitaddress is a list of strings.
I just don't know why its throwing the error and mentioning an integer.

Me.Controls is of type ControlCollection and it is expecting a parameter of type integer, but you are providing a parameter of type string.
To find a control on the page you can use a method FindControl of class Page. You can see the info in MSDN.
You can update your code to use this method:
Dim myLabel As Label = CType(Me.FindControl("lbladdress" & (i + 1).ToString()), Label)

Related

Convert from string to textbox object

I am trying to convert a string to textbox, but I am getting an error that it cannot convert to integer?!
I have the following code:
Dim curr As String
curr = "Detail_0107"
Dim NEWTEXT As TextBox = TryCast(Me.Controls(curr), TextBox)
NEWTEXT.Text = "test"
On the TryCast, I get the following error:
Conversion from string "Detail_0107" to type 'Integer' is not valid
Detail_0107 is a textbox on my form. Can I do this?
Thanks
Your problem seems to be that you're setting Detail_0107 as a string. If you want to set the text of Detail_0107, all you need to do is the following:
Detail_0107.Text = "test"
As you said Detail_0107 is already a textbox on your form, there shoud already be an object for it.
Try using Me.Controls.Find(curr) instead. Additionally, every control has a .Text property. It's part of the base Control type, and therefore you have no need to cast to TextBox. If you're very sure the Detail_0107 control does exist in that collection, you can get the code down to just this:
Me.Controls.Find("Detail_0107").Text = "test"

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.

Simple bind value to textbox in code behind using Telerik OpenAccess

I cannot find a complete example. Found tons on grid and combobox, but not textbox. This test is to lookup a “PhoneTypeName” from a UserPhoneType table with TypeCode = “0” and assign that first value to a asp.net textbox.
Currently, I am getting “Object reference not set to an instance of an object” when setting the text box to "phonetype.FirstOrDefault.PhoneTypeName.ToString"
Using dbContext As New EntitiesModel()
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode = "O")
mytextbox.Text = phonetype.FirstOrDefault.PhoneTypeName.ToString
End Using
----EDIT----
I changed as suggested. I ALSO successfully bound the entire list of PhoneTypes to a droplist control...to confirm the data is accessible. It must be the way I am going about querying the table for a single record here.
I get the same error, but at "Dim type = phonetype.First..."
The record is in the table, but it does not appear to be extracted with my code.
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext1.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode = "M")
Dim type = phonetype.FirstOrDefault
If Object.ReferenceEquals(type, Nothing) = False And Object.ReferenceEquals(type.PhoneTypeName, Nothing) = False Then
mytextbox.Text = type.PhoneTypeName.ToString
End If
In general there are the following two possible reasons for getting this exception:
1) The phonetype list is empty and the FirstOrDefault method is returning a Nothing value.
2) The PhoneTypeName property of the first element of the phonetype list has a Nothing value.
In order to make sure that you will not get the Object reference not set to an instance of an object exception I suggest you add a check for Nothing before setting the TextBox value. It could be similar to the one below:
Dim type = phonetype.FirstOrDefault
If Object.ReferenceEquals(type, Nothing) = False And Object.ReferenceEquals(type.PhoneTypeName, Nothing) = False Then
mytextbox.Text = type.PhoneTypeName.ToString
End If
Fixed it.
I was able to view the SQL string being generated by using this:
mytextbox.text = phonetype.tostring
I saw that the SQL contained "NULL= 'O'"
I did it like the example?!? However, when I added .ToString to the field being queried, it worked.
So the final looks like this:
Using dbContext As New EntitiesModel()
Dim phonetype As IEnumerable(Of User_PhoneType) = dbContext.User_PhoneTypes.Where(Function(c) c.PhoneTypeCode.**ToString** = "O")
mytextbox.Text = phonetype.FirstOrDefault.PhoneTypeName.ToString
End Using
BTW, Dimitar point to check for null first is good advice (+1). The value was nothing as he said.

Dynamically Reference an Object Property Using a String

I'm trying to reference a public property from a string. How can this be done in vb.net?
I have the text value of "FirstName" stored in strucParam(i).TxtPropertyName.
This is what I'm currently doing:
Dim tmpValue As String
Dim ucAppName As UserControl_appName = CType(Parent.FindControl(strucParam(i).ParentFindControl), UserControl_appName)
tmpValue = ucAppName.FirstName.Text
How can I use the value in strucParam(i).TxtPropertyName so that I can remove ".FirstName" from my code? Thanks!
This is basically a duplicate of this question, but I'll answer it for you since you're a VB user and probably didn't consider C# in your searches.
Suppose you have an object of any type stored in a variable called objObject, and the name of the property stored in a variable called strPropertyName. You do the following:
tmpValue = objObject.GetType().GetProperty(strPropertyName).GetValue(objObject, Nothing)
As a final note: please, please consider dropping pseudo-Hungarian notation. It's of no value when working with a statically typed language like VB.NET.
Edit:
The FirstName property is in reality a text box. So don't I need to somehow reference .Text in the code?
tmpFirstName = ucAppName.GetType().GetProperty(strucParam(i).PropertyName).GetValue(objAppNav, Nothing)
Try this:
Dim textBox as TextBox
Dim tmpValue as String
textBox = CType(ucAppName.GetType().GetProperty(strucParam(1).PropertyName).GetValue(objAppNav, Nothing), TextBox)
tmpValue = textBox.Text
Basically, you have to cast the value of the property to a TextBox type, then grab the Text property from it.

Resources