FindControl in Asp.Net - asp.net

I'm trying to find a control in a page. The Id is available as a server control (CheckBox)
This throws exception "not able to convert string to double"
Dim taskId As HtmlInputCheckBox
i =10
taskId = Me.FindControl("chkTaskOption_" + i)
taskId.Checked = True
Can any one tell me where i'm wrong.

Your problem is that you need to use & instead of + to concatenate two strings in VB.NET. Change this line:
taskId = Me.FindControl("chkTaskOption_" & i)
For further reading, there's a good discussion about this in the answers to this question.

You might just be missing a cast of the type returned from FindControl. Or on the variable i. I can't remember if VB.net will convert for you.
i =10
Dim taskId As HtmlInputCheckBox
taskId = CType(Me.FindControl("chkTaskOption_" & i.ToString()), HtmlInputCheckBox)
taskId.Checked = True

Related

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

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)

The given key was not present in the dictionary. VB.NET

I'm trying to debug an issue I didnt create and I'm getting the generic error "The given key was not present in the dictionary." Here is the code:
Dim myInfo As New Dictionary(Of Integer, String)
For i As Integer = 0 To Region.GetRegionCount - 1
myInfo.Add(i, Server.HtmlEncode(ContentItem.Properties("StoreInfoRegion" & i).Value.ToString))
Next
Session(SESSION_INFO) = myInfo
When I step thru it the error occurs on the call to "Add", I guess Im confused because it's adding a key not trying to access one.
Thanks!
You have a pretty big line of code, split it up into it's pieces and you might find where the problem is exactly.
Instead of
myInfo.Add(i, Server.HtmlEncode(ContentItem.Properties("StoreInfoRegion" & i).Value.ToString))
Have
Dim propertyValue As String
propertyValue = ContentItem.Properties("StoreInfoRegion" & i).Value.ToString
propertyValue = Server.HtmlEncode(propertyValue)
myInfo.Add(i, propertyValue)
With this change, I'm pretty sure that you will see the error on the 2nd line where you fetch the value of Properties. This mean you do not have a value for "StoreInfoRegion" & i
You could do
If ContentItem.Properties.ContainsKey("StoreInfoRegion" & i) Then
Dim propertyValue As String
propertyValue = ContentItem.Properties("StoreInfoRegion" & i).Value.ToString
propertyValue = Server.HtmlEncode(propertyValue)
myInfo.Add(i, propertyValue)
End If
But I think you should first understand why there are no value for that key first.

Conversion from string "ACECATN000001" to type 'Integer' is not valid

I am a new in using asp.net i have recieving an error of "Conversion from string "ACECATN000001" to type 'Integer' is not valid." can anyone help me how to solve this?? thanks in advance :D
If lbl_productcatcode.Text = "ACECATN000001" Then
txt_productcode.Text = Format(CInt(rdr.Item(0).ToString) + 1, "1000000")
End If
End If
cmd1.Connection.Close()
End Sub
You've posted some code but not said which line has the error, I presume it is this one:
cmd1.CommandText = "Select CategoryID from CategoryTable where ProductCategory = '" & DropDownList1.Text & "'"
If the CategoryId column on the CategoryTable is of type integer, then you cannot compare it against a string value. I would guess that you need to use the ID of the item bound to the DropdownList, IIRC there should be a SelectedValue property on the dropdown that you can use for this.
cmd1.CommandText = "Select CategoryID from CategoryTable where ProductCategory = " & DropDownList1.SelectedValue
Note the absense of single quotes as you will be injecting an int value into the sql statement.
Firstly: CInt(s) converts s(s being a string) to integer and is only valid if s contains only numbers(no letters).
In this line:
txt_productcode.Text = Format(CInt(rdr.Item(0).ToString) + 1, "1000000")
you are trying to convert rdr.Item(0).ToString to an integer. According to your code,
rdr.Item(0).ToString returns "ACECATN000001" which contains letters and hence cannot be converted to integer.
What exactly are u wanting to do in that line?

Error while using DataTable.Select() Method in Vb.Net

I am using DataTable.Select() method to filer based on some conditions.
dtRows = m_dtTable.Select(String.Format("IdentifierID={0}", dtRow
("QuestionID").ToString))
I used the similar way to sort the data in different places . But only one place i am getting error.
Can any help me to find why this exception is occurs? Also help me to know why there is no exception in other places ? The values of datatable is filled from a stored procedure.
Min (2) must be less than or equal to max (-1) in a Range object. is exception I am getting.
EDIT -- After the First Answer --
I am getting exception not every time, but only some time that I cannot identify the scenario. :(
ADDED -- After the First Answer --
Thanks for the solution. :)
Note : m_DependantQuestionsDataTable and m_dtTable are same by its schema.
colIdentifierID.DataType = Type.GetType("System.String")
colIdentifierID.ColumnName = "IdentifierID"
This is the type of particular column. There is also another column which is also similar type and there is no error occurs when I use it with the similar method.
colQuestionID.DataType = Type.GetType("System.String")
colQuestionID.ColumnName = "QuestionID" is the column and I am using like this. ' Dim strFilterExpression As String = "questionID={0}" m_DependantQuestionsDataTable.Select(String.Format(strFilterExpression, dRow("QuestionID")))'
Here there is no exception or error is occurring . So if I am choosing your solution I need to change the Filter Expression by adding ' in all place in my solution where I am using Filter Method.
You don't specify the data type of the column you're filtering on and if it's a string then you'll need to add single quotes around the parameter in your filter expression:
dtRows = m_dtTable.Select(String.Format("IdentifierID='{0}'", dtRow("QuestionID").ToString()))
alternatively, if you want to sort+ filter via the DGV, without need to repopulate the DT and DGV, you can use .Sort and .RowFilter of the DataView
http://msdn.microsoft.com/en-ca/library/system.data.dataview.rowfilter.aspx
Private _DS As New DataSet
Private _DT As New DataTable
Private _DV As New DataView
Private _DGV As New DataGridView
Private _isFiltering As Boolean = False
Private Sub filterView()
If _isFiltering Then Return
_isFiltering = True
Dim _SF As String = "price ASC"
'Dim _RF As String = tableStructure.Columns(0).Name & " < 20" ' just an example
Dim _RF As String = "price < 20"
_DGV.ClearSelection()
_DT.DefaultView.Sort = _SF
_DT.DefaultView.RowFilter = _RF
_isFiltering = False
End Sub

Compare values from data source to string

I'm just stumped on what to do with this code, I'm just trying to implement a 'no duplicates' catch on my insert customer form, but it just slips through my if statement to the else everytime. This is the source. Also I tried a .Equals with the same results :(
Protected Sub srcAllClients_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles srcAllClients.Inserting
'Establish Variables
Dim emailAddress As String
Dim srcUsers As SqlDataSource = New SqlDataSource()
srcUsers.ConnectionString = ConfigurationManager.ConnectionStrings("ISSD21ConnectionString").ConnectionString
Dim view As DataView
view = DirectCast(srcUsers.Select(DataSourceSelectArguments.Empty), DataView)
srcUsers.SelectCommand = "SELECT EmailAddress FROM ISSDClients"
srcUsers.DataSourceMode = SqlDataSourceMode.DataReader
Dim reader As IDataReader
reader = DirectCast(srcUsers.Select(DataSourceSelectArguments.Empty), IDataReader)
emailAddress = FormView1.FindControl("txtEmail").ToString
While reader.Read()
If reader("EmailAddress") = (emailAddress) Then
lblError.Text = "Your Email is NOT Unique!"
'this is where we cancel the update and return an error
Else
lblError.Text = "Your Email is Unique!"
'nothing needs to happen, maybe just tell them that it went through
End If
End While
reader.Close()
End Sub
emailAddress = FormView1.FindControl("txtEmail").ToString
is just going to return the string "System.Web.UI.WebControls.TextBox". You're not accessing the actual property of the control that would hold the text value, you're just calling ToString() on the control itself.
Try this:
Dim emailBox As TextBox = CType(FormView1.FindControl("txtEmail"), TextBox);
emailAddress = emailBox.Text
In addition to Womp's answer...
In the while loop that is running through the email records, you need to break out of the loop once you find a matching email and alert the user.
if reader("EmailAddress") = (emailAddress) then
'1. Break from the Loop
End if
I would recommend that you pass the emailAddress to the SQL Server as a parameter.
Select Count(EmailAddress) From ISSDClients
Where EmailAddress = #EmailAddress
Execute this statement using ExecuteScalar and cast the result as an integer. If the result is zero then you are ok, otherwise display an error.
Doing it this way avoids using the while loop and should be much quicker if your table has lots of rows.
You also need to get the Text property from the Email Text box.
emailAddress = FormView1.FindControl("txtEmail").Text.ToString
You may want to take a look at the String.Compare method, which will make it easier to compare without respect to things like case sensitivity and culture. It does consider whitespace to be part of your string, so you may wish to trim the string prior to calling it, to help normalize.
For example, the following strings would be considered equal:
var firstString = "some StrinG to Compare ";
var secondString = " somE string to COMPARE";
var equal = (String.Compare(firstString.Trim(), secondString.Trim(), StringComparison.InvariantCultureIgnoreCase) == 0);

Resources