I am trying to compare a session variable to another string so that i can enable or disable image buttons. I am using asp.net vb with a sql2005 express backend
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim string1 As String
Dim string2 As String
Label1.Text = Session("Username")
Label2.Text = Session("UserId")
string1 = Session("Username")
string2 = "medev"
If String.Compare(string1, string2, True) = 1 Then
ImageButton1.Enabled = False
End If
String.Compare returns -1, 0 or 1 depending on the result:
String.Compare("A", "B", true) ' returns -1 '
String.Compare("B", "A", true) ' returns 1 '
String.Compare("B", "B", true) ' returns 0 '
In your case, ImageButton1 will be disabled if the user name would come before "medev" if you sorted them as a list. So "Adam" wound have it disabled, while "Stuart" would have it enabled. "medev" would also get it disabled, because if the strings are equal, String.Compare returns 0. My guess is that you want ImageList1 enabled for "medev":
If String.Compare(string1, string2, True) <> 0 Then
ImageButton1.Enabled = False
End If
I would also suggest using the String.Compare overload that takes a StringComparison instead of a bool to get a case insensitive compare. In my opinion it makes it a lot easier to understand what the code does:
If String.Compare(string1, string2, StringComparison.InvariantCultureIgnoreCase) <> 0 Then
ImageButton1.Enabled = False
End If
String Compare returns 0 if the strings are equal. To evaluate for true change your comparison to = 0 rather than <> 0.
If String.Compare(string1, string2, StringComparison.InvariantCultureIgnoreCase) = 0 Then
If you envision performing such checks frequently to display different portions of a page you might want to break your pages up based on the different types (or levels) of users you expect and redirect them to a particular page upon login. Depending on how similar the pages are between users you'll likely find using master pages and/or user controls to be beneficial.
this is works!
ImageButton1.Enabled = Not Session("UserName") Is Nothing AndAlso Session("UserName").ToString.ToLower.Trim.Equals("username")
ImageButton2.Enabled = Not Session("UserName") Is Nothing AndAlso_ Session("UserName").ToString.ToLower.Trim.Equals("username")
Related
as the title states I am trying to compare or validate a text box entry against a list of acceptable values stored in my database. As of now I have taken the values from my database and store them in a List(of String) and I have a for loop that loops through that list and returns true if the values match, if the values do not match it will return false. Below I have attached the code I am currently working with.
Protected Sub txtSearchOC_TextChanged(sender As Object, e As EventArgs) Handles txtSearchOC.TextChanged
Dim listEType As List(Of String) = New List(Of String)
Dim eType As String = txtSearchOC.Text
Dim strResult As String = ""
lblPrefix.Text = ""
lblList.Text = ""
Dim TypeIDQuery As String = "
SELECT a.OrderCode
FROM SKU AS a
INNER JOIN EnrollmentType AS e ON a.EnrollmentTypeID = e.TypeID
INNER JOIN Enrollment AS f ON e.RecID = f.EnrollmentTypeID
WHERE f.AccountNumber = '12345';
"
Using connEType As New SqlConnection(ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ToString)
Using cmdEType As New SqlCommand(TypeIDQuery, connEType)
cmdEType.Parameters.Add("#AccountNumber", SqlDbType.VarChar, 15).Value = "12345"
connEType.Open()
Using sdrEType As SqlDataReader = cmdEType.ExecuteReader
While sdrEType.Read
listEType.Add(sdrEType("OrderCode").ToString)
End While
End Using
End Using
End Using
For Each Item As String In listEType
strResult &= Item & ", "
Next
For i = 0 To listEType.Count - 1
If eType = listEType(i) Then
lblPrefix.Text = "True"
End If
If eType <> listEType(i) Then
lblList.Text = "Error"
End If
Next
'lblList.Text = strResult
End Sub
In the code I declare my list and a variable to store the text value of the text box. To verify that it pulled the appropriate values from the database I have the strResult variable and can confirm that the appropriate values are being stored.
The problem I am having has to do with the For loop I have at the bottom, when I enter in a valid value that is contained in the listEType, I get the confirmation message of "True" indicating it has matched with one of the values, but I also get the "Error" message indicating that it does not match. If I enter in a value that is not contained in the list I only get the "Error" message which is supposed to happen.
My question is, based on the code I have supplied, why would that For loop be returning both "True" and "Error" at the same time for a valid entry? Also, if there is a better way to accomplish what I am trying to do, I am all ears so to speak as I am relatively new to programming.
Well, as others suggested, a drop down (combo box) would be better.
However, lets assume for some reason you don't want a combo box.
I would not loop the data. You have this amazing database engine, and it can do all the work - and no need to loop the data for such a operation. Why not query the database, and check for the value?
Say like this:
Protected Sub txtSearchOC_TextChanged(sender As Object, e As EventArgs) Handles txtSearchOC.TextChanged
If txtSearchOC.Text <> "" Then
Dim TypeIDQuery As String = "
SELECT a.OrderCode FROM SKU AS a
INNER JOIN EnrollmentType AS e ON a.EnrollmentTypeID = e.TypeID
INNER JOIN Enrollment AS f ON e.RecID = f.EnrollmentTypeID
WHERE f.AccountNumber = #AccoutNumber;"
Using connEType As New SqlConnection(ConfigurationManager.ConnectionStrings("WarrantyConnectionString").ToString)
Using cmdEType As New SqlCommand(TypeIDQuery, connEType)
cmdEType.Parameters.Add("#AccountNumber", SqlDbType.NVarChar).Value = txtSearchOC.Text
connEType.Open()
Dim rstData As New DataTable
rstData.Load(cmdEType.ExecuteReader)
If rstData.Rows.Count > 0 Then
' we have a valid match
lblPrefix.Text = "True"
Else
' we do not have a valid match
lblPrefix.Text = "False"
End If
End Using
End Using
End If
End Sub
So, pull the data into a data table. You can then check the row count, or even pull other values out of that one row. But, I don't see any need for some loop here.
I have to make my previous stand alone project into a web application. Everything works OK, for the most part, however my counter is not. The user has an option to see how many answers they are getting correct and incorrect. I copied most of my code from the original project with the exception of a few tweeks... idk what I'm not doing right.
When you input a correct answer nothing shows, but when you input a wrong answer it shows
correct:0 incorrect:1 and it doesn't change. I tried with making numCorrect and numIncorrect equal 0 as seen below... still nothing.
Any help will be greatly appreciated!
Protected Sub CheckButton_Click(sender As Object, e As EventArgs) Handles CheckButton.Click
'assign numbers to variable for calculation
Dim correctAnswer As Integer
Dim numCorrect As Integer = 0
Dim numIncorrect As Integer = 0
num1 = CInt(Val(FirstNumLabel.Text))
num2 = CInt(Val(SecondNumLabel.Text))
answerNum = CInt(Val(AnswerTextBox.Text))
'calculate the correct answer
Select Case OperationsRadioButtonList.SelectedIndex = 0
Case True
'addition operation
correctAnswer = num1 + num2
Case False
'subtraction operation
correctAnswer = num1 - num2
End Select
'tell user if their input is correct or incorrect
'show images and messages when answer is correct
If answerNum = correctAnswer Then
MessageLabel.Text = "Nice Job!"
HFaceImage.Visible = True
SFaceImage.Visible = False
'add count for numbers correct to summary
numCorrect += 1
'clear textbox for new input and focus to textbox for new
With AnswerTextBox
.Text = ""
.Focus()
End With
'generate new random set
Call RandomNumberGenerator()
Else 'show image and message if answer is incorrect
SFaceImage.Visible = True
HFaceImage.Visible = False
'add count for numbers incorrect to summary
numIncorrect = numIncorrect + 1 '
'display message if incorrect answer was given
MessageLabel.Text = "Try Again!"
'clear textbox for new input and focus to textbox
With AnswerTextBox
.Text = ""
.Focus()
End With
'show the number of correct and incorrect input when summaryCheckBox is checked
If CheckBox.Checked Then
CorrectCounterTextBox.Text = CStr(Val(numCorrect))
IncorrectCounterTextBox.Text = CStr(Val(numIncorrect))
Else
CorrectCounterTextBox.Text = ""
IncorrectCounterTextBox.Text = ""
End If
End If
End Sub
You set the CorrectCounterTextBox and IncorrectCounterTextBox text property inside the wrong answer code block, that is why the labels don't get updated when user gave correct answer. Take it out of the If ... Else ... End If block like below:
'tell user if their input is correct or incorrect
'show images and messages when answer is correct
If answerNum = correctAnswer Then
' your existing code
Else 'show image and message if answer is incorrect
SFaceImage.Visible = True
HFaceImage.Visible = False
'add count for numbers incorrect to summary
numIncorrect = numIncorrect + 1 '
'display message if incorrect answer was given
MessageLabel.Text = "Try Again!"
'clear textbox for new input and focus to textbox
With AnswerTextBox
.Text = ""
.Focus()
End With
' your existing code moved out to below.
End If
'show the number of correct and incorrect input when summaryCheckBox is checked
If CheckBox.Checked Then
CorrectCounterTextBox.Text = CStr(Val(numCorrect))
IncorrectCounterTextBox.Text = CStr(Val(numIncorrect))
Else
CorrectCounterTextBox.Text = ""
IncorrectCounterTextBox.Text = ""
End If
PS: You might want to remove the Dim numCorrect As Integer = 0 and Dim numIncorrect As Integer = 0 lines at the top of your code, otherwise your counters will never get incremented. Save the counters into Session or Viewstate instead.
I have a form with many drop down list boxes on. Each of which I am showing or hiding a row of a table based on its value then adding a requiredfieldvalidator to the text box contained in that row. I am doing this on the selectedindexchanged event of each drop down list, the code for which can be seen below:
Protected Sub cbOffCover_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbOffCover.SelectedIndexChanged
If cbOffCover.SelectedValue = "N" Then
OffCoverRow.Visible = True
Dim rfOffcover As RequiredFieldValidator = New RequiredFieldValidator
With rfOffcover
.ControlToValidate = txtOffCover.ID
.SetFocusOnError = True
.ErrorMessage = "*"
.ForeColor = System.Drawing.Color.Red
End With
OffCoverCell.Controls.Add(rfOffcover)
Else
OffCoverRow.Visible = False
Dim c As Control
For Each c In OffCoverCell.Controls
If c.ID = "rfOffCover" Then
OffCoverCell.Controls.Remove(c)
End If
Next c
End If
End Sub
I then reuse this code for each drop down list to show/hide a differently named row and apply validation to a different text box.
My question being is there a better way of doing this? I don't know exactly how but I can't help but think I don't have to write this much code (or copy/paste) over and over again for each drop down list. Is it possible to write a function/class that will do the work and I can just call that instead? Might seem basic but i'm new to asp/vb. Many thanks
You can put it in a function that returns a boolean. When you call the function, pass it the combobox itself and whatever values you want to validate against. If it matches, return true. Try something like this:
Public Function ValidateComboBox(someComboBox as ComboBox, expectedValue as String)
Dim result as Boolean = False
If someComboBox.SelectedValue = expectedValue Then
result = True
OffCoverRow.Visible = True
Dim rfOffcover As RequiredFieldValidator = New RequiredFieldValidator
With rfOffcover
.ControlToValidate = txtOffCover.ID
.SetFocusOnError = True
.ErrorMessage = "*"
.ForeColor = System.Drawing.Color.Red
End With
OffCoverCell.Controls.Add(rfOffcover)
Else
OffCoverRow.Visible = False
Dim c As Control
For Each c In OffCoverCell.Controls
If c.ID = "rfOffCover" Then
OffCoverCell.Controls.Remove(c)
End If
Next c
End If
Return result
End Function
Of course, modify it to fit your needs. Maybe you only return the value, and do the other stuff inside the control's SelectedIndexChanged method.
I have a gridview which can be filtered from one or more values in a querystring. That all works great: e.g. "?subject=Maths&authorName=Bond_James&type=Magazine"
The values passed to the query string come from 3 drop down lists: Subject, Author, Type.
What I'd like is when the user presses "Filter" it will take the selected values from the drop down lists and pass them to the querystring - it could be 1 value, 2, or all 3 (like above).
The drop down lists have an item called "All Subjects" / "All Author" / "All Type" each with a value of -1. The idea being that if the user leaves these items selected then the Filter button just ignores them.
Here is my code so far:
Protected Sub buttonFilterGo_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonFilterGo.Click
Dim queryString As String
Dim selectedAuthorString As String = "author=" & dropAuthorList.SelectedItem.Value
Dim selectedSubjectString As String = "subject=" & dropSubjectList.SelectedItem.Value
Dim selectedTypeString As String = "type=" & dropPaperType.SelectedItem.Value
Const PATH As String = "~/paper/browse/?"
queryString = selectedAuthorString & "&" & selectedSubjectString & "&" & selectedTypeString
If IsNothing(queryString) Then
labelFilterFeedback.Text = "Apply some filters then press Go"
Else
Response.Redirect(PATH & queryString)
labelFilterFeedback.Text = ""
End If
End Sub
Also, one more thing. How do I get the drop down lists to have the filters selected when the page re loads?
I'd really appreciate any help!
EDIT: I changed the default values of the drop down lists to "" - this leaves the URL looking messy though ?author=&subject=&type= This works, is it the best way?
I am not a VB person, so forgive any syntax errors. This approach will only add the query string if there are values, and only add terms for those parameters with values. I used "!="as the Not Equal operator. I am not sure if VB uses "<>" instead. Please consider this more as pseudo-code to illustrate the idea.
Dim queryString As String = "?"
...
Const PATH As String = "~/paper/browse/"
...
If dropAuthorList.SelectedItem.Value != "" Then
queryString = queryString & selectedAuthorString
EndIf
If dropSubjectList.SelectedItem.Value != "" Then
If querystring.Length > 1 Then
queryString = queryString + "&"
EndIf
queryString = queryString & selectedSubjectString
EndIf
If dropPaperType.SelectedItem.Value != "" Then
If querystring.Length > 1 Then
queryString = queryString + "&"
EndIf
queryString = queryString & selectedTypeString
EndIf
If querystring.Length = 1 Then
queryString = ""
EndIf
You can continue to use your empty string value and I would tend to prefer this to an assigned value, even though -1 is usually a good choice since it's highly unlikely that one of your filters would be using that as a value. I would clean up your query string though by calling something like the following function:
Private Function AppendFilter(ByVal filterName As String, ByVal filterVal As String, ByVal query As String) As String
Dim res As String = query
If filterVal.Length() > 0 Then
res = IIf(query.Length() > 0, query & "&", query) & filterName & "=" & filterVal
End If
Return res
End Function
instead of this line from your code: queryString = selectedAuthorString & "&" & selectedSubjectString & "&" & selectedTypeString
Your resulting code would look like this:
Protected Sub buttonFilterGo_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonFilterGo.Click
Dim queryString As String = ""
Const PATH As String = "~/paper/browse/?"
queryString = AppendFilter("author", dropAuthorList.SelectedItem.Value, queryString)
queryString = AppendFilter("subject", dropSubjectList.SelectedItem.Value, queryString)
queryString = AppendFilter("type", dropPaperType.SelectedItem.Value, queryString)
If queryString.Length() <= 0 Then
labelFilterFeedback.Text = "Apply some filters then press Go"
Else
Response.Redirect(PATH & "?" & queryString)
labelFilterFeedback.Text = ""
End If
End Sub
And your query string won't contain filters that aren't applicable.
I am trying to compare a session variable to another string so that i can enable or disable image buttons. I am using asp.net vb with a sql2005 express backend
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim string1 As String
Dim string2 As String
Label1.Text = Session("Username")
Label2.Text = Session("UserId")
string1 = Session("Username")
string2 = "medev"
If String.Compare(string1, string2, True) = 1 Then
ImageButton1.Enabled = False
End If
String.Compare returns -1, 0 or 1 depending on the result:
String.Compare("A", "B", true) ' returns -1 '
String.Compare("B", "A", true) ' returns 1 '
String.Compare("B", "B", true) ' returns 0 '
In your case, ImageButton1 will be disabled if the user name would come before "medev" if you sorted them as a list. So "Adam" wound have it disabled, while "Stuart" would have it enabled. "medev" would also get it disabled, because if the strings are equal, String.Compare returns 0. My guess is that you want ImageList1 enabled for "medev":
If String.Compare(string1, string2, True) <> 0 Then
ImageButton1.Enabled = False
End If
I would also suggest using the String.Compare overload that takes a StringComparison instead of a bool to get a case insensitive compare. In my opinion it makes it a lot easier to understand what the code does:
If String.Compare(string1, string2, StringComparison.InvariantCultureIgnoreCase) <> 0 Then
ImageButton1.Enabled = False
End If
String Compare returns 0 if the strings are equal. To evaluate for true change your comparison to = 0 rather than <> 0.
If String.Compare(string1, string2, StringComparison.InvariantCultureIgnoreCase) = 0 Then
If you envision performing such checks frequently to display different portions of a page you might want to break your pages up based on the different types (or levels) of users you expect and redirect them to a particular page upon login. Depending on how similar the pages are between users you'll likely find using master pages and/or user controls to be beneficial.
this is works!
ImageButton1.Enabled = Not Session("UserName") Is Nothing AndAlso Session("UserName").ToString.ToLower.Trim.Equals("username")
ImageButton2.Enabled = Not Session("UserName") Is Nothing AndAlso_ Session("UserName").ToString.ToLower.Trim.Equals("username")