Checking content of textbox vb.net - asp.net

I am using a text box for input to my SQL query. Based on the input I create a certain query and display the data in a gridview.
However I wish to make an adjustment for my users.
They often make an input like PL26... However this is not a valid name in the database to search for. Therefore I want to CHECK their input, and alter it accordingly, so they don't have to think about it.
I happen to know that when they type PL26 the correct input would be PL000026 ... The entity to search for is always "PL" + 6 characters/numbers... so if they wrote PL155, the number/string I pass to the sql query should become PL + 000 + 155 = PL000155.
I hope someone can help me how to accomplish this. That is if it is possible?
My idea/Pseudo code would be something like
If tbInput.txt's FIRST 2 CHARS are PL, then check total length of string
if StringLength < 8 characters, then
if length = 2 then ADD 4 0' after PL...
if length = 3 then add 3 0's after PL...
if length = 3 then add 3 0's after PL..
etc
....
...

Here we go:
Private Sub Button21_Click(sender As System.Object, e As System.EventArgs) Handles Button21.Click
Debug.Print(formatCode("PL1"))
Debug.Print(formatCode("PL"))
Debug.Print(formatCode("PL01"))
Debug.Print(formatCode("PL155"))
End Sub
Private Function formatCode(userInput As String) As String
Dim returnVal As String
If userInput.Length < 8 Then
returnVal = String.Concat(userInput.Substring(0, 2), userInput.Substring(2, userInput.Length - 2).PadLeft(6, "0"))
Else
returnVal = userInput
End If
Return returnVal
End Function
You may need to add some validation ensuring it starts with PL etc.

The following will work as long as there are no other non-numeric characters in between the PL and the numbers. You can always add it in your validation.
Dim newInput As String
If (input.StartsWith("PL")) Then
input = input.Remove(0, 2)
End If
' If this fails then it means the input was not valid
Dim numberPart = Convert.ToInt32(input)
newInput = "PL" + numberPart.ToString("D6")

Exctract a number by removing prefix "PL"
Parse to Integer
Use Custom Numeric Format Strings(zero placeholder) for adding zeros and prefix
Const PREFIX As String = "PL"
Dim exctractedNumber As Int32
If Int32.TryParse(tbInput.txt.Replace(PREFIX, String.Empty), exctractedNumber) = False Then
'Error nahdling
Exit Sub
End If
Dim finalFormat As String = String.Format("'{0}'000000", PREFIX)
Dim finalValue As String = exctractedNumber.ToString(finalFormat)

I would make use of the handy PadLeft method:
Dim input As String = "PL26"
Dim number As String = input.Substring(2, input.Length - 2)
If number.Length <> 6 Then
number = number.PadLeft(6, "0"C)
End If
MSDN String.PadLeft

Related

How to sum a column from a running total data table in VB.NET?

I am currently working on a project and am running into an error that says: Syntax error in aggregate argument: Expecting a single column argument with possible 'Child' qualifier. I have a column named "Total#" in a BusinessAnalytics data table. I want to sum the column together so that I can use it to calculate a percentage of members and percentage of nonmembers. How can I fix this?
My code for a data table with running totals
Dim decTotalNumber As Decimal
Dim decPercentSales As Decimal
Dim intRow As Integer
If chkRewards.Checked = True Then
intRow = 1 'member
Else
intRow = 0 'nonmember
End If
With BusinessAnalytics.Rows(intRow)
.Item("Total#") += 1
decTotalNumber = BusinessAnalytics.Compute("SUM(Total#)", Nothing)
decPercentSales = Convert.ToDecimal(.Item("Total#")) / decTotalNumber
.Item("%Total") = decPercentSales.ToString("P1")
End With
GridView3.DataSource = BusinessAnalytics
GridView3.DataBind()
Your column name contains non-alphanumeric characters, so it should be wrapped in square brackets or "`" (grave accent) quotes.
Expression
So your statement should be:
decTotalNumber = BusinessAnalytics.Compute("SUM([Total#])", Nothing)

User Form multi-selection Listbox arrays or entirerow.copy?

Amateur her so bear with me. I am trying to compile VBA code which runs a userform with list box populated with a 9 column and 100 row table from worksheet1. The user selects the only the items in the list box he needs for a report and they are to copied to worksheet 2.
With help from a 6 year old post on this site, I have managed to do this using an array and a public function to select the chosen rows and then output them to worksheets2. As follows:
Private Sub CommandButton1_Click()
Dim SelectedItems() As Variant
Dim i As Integer
Dim emptyrow As Integer
wsTarget.Activate
Range("A1").Select
SelectedItems = GetSelectedRisks(RiskList)
emptyrow = 15
For i = LBound(SelectedItems) To UBound(SelectedItems)
wsTarget.Cells(emptyrow, 2).Value = SelectedItems(i)
emptyrow = emptyrow + 1
Next
End Sub
Public Function GetSelectedRisks(lBox As MSForms.ListBox) As Variant
Dim tmpArray() As Variant
Dim i As Integer
Dim SelectionCounter As Integer
SelectionCounter = -1
For i = 0 To lBox.ListCount - 1
If lBox.Selected(i) = True Then
SelectionCounter = SelectionCounter + 1
ReDim Preserve tmpArray(SelectionCounter)
tmpArray(SelectionCounter) = lBox.List(i)
End If
Next
However I can only work out how to do this for the 1st column. I just can't work out how to get the other columns into the array and then back out again.
Should I be using an array or am I making this to complicated i.e. should I just be using loops and if selected, entirerow.copy type stuff?

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

I get the following error when trying to create a default row in the asp.net dropdown: Conversion from string "x" to type 'Integer' is not valid.
CmbSalesAgents is the drop down control.
DefaultSalesAgent is the entity object (has values)
x is a concatenation of a numeric value and a string
**
Dim DefaultSalesAgent = (From o In db.PayoutRegisters
Join s In db.SalesAgents On s.SalesAgentId Equals o.SalesAgentID
Where o.PayoutRegisterID = PayoutRegisterID
Select o.PayoutRegisterID, x = s.CSRName + " (" + o.PaidThruDate.ToString + ")").ToList
If DefaultSalesAgent.Count > 0 Then
CmbSalesAgents.Items.Insert(0, New ListItem(DefaultSalesAgent.Item("x").ToString, PayoutRegisterID))
Else
CmbSalesAgents.Items.Insert(0, New ListItem("Select Sales Agent Payout Register", 0))
End If
Since DefaultSalesAgent is a list object then you should access its items through integer index not a string:
DefaultSalesAgent.Item(integer_index)
If you specifically need to insert the row based off a string value, you can replace
DefaultSalesAgent.Item("x")
With
DefaultSalesAgent.Item(DefaultSalesAgent.FindIndex(x => x.StartsWith("x")));
You can also use contains instead of startswith depending on your needs. Please note this is only if you specifically need to look for strings as it's a lot more expensive than accessing an index in the list.

Dynamically count of similar kind of Data

I have one data table in VB page which contain bulk data.In that data table one column named as vType and values in that column is one of Pr defined values such as 'A','B','C','D' etc , which comes from one Datable.
Now I want count of each type at the end.
For ex : CountA = 20,CountB=25 and so on .
Till now I have compared Each value using If condition which is static
For each dr as dataRow in dsType.rows
If dr("vType") = 'A' Then
CountA += 1
ElseIf dr("vType") = 'B' Then
CountB +=1
Next dr
and this If condition will repeat depend upon no of types in that data table (at max 8 fix values) I want to do this in single if condition ( Dynamic if Possible) Can I Count these values and store the same into single varaible? appreciate for you prompt reply.
You can use Linq-To-DataSet and Enumerable.GroupBy + Enumerable.Count on each group:
Dim typeGroups = dsType.AsEnumerable().
GroupBy(Function(row) row.Field(Of String)("vType")).
Select(Function(g) New With{ .Type = g.Key, .Count = g.Count(), .TypeGroup = g })
Note that New With creates an anonymous type in VB.NET with custom properties. So like a class on-the-fly which you can use in the current method.
Now you can enumerate the query with For Each:
For Each typeGroup In typeGroups
Console.WriteLine("Type:{0} Count:{1}", typeGroup.Type, typeGroup.Count)
Next
I cannot use Linq, i need to use simple vb only
Then use a Dictionary:
Dim typeCounts = New Dictionary(Of String, Integer)
For Each row As DataRow In dsType.Rows
Dim type = row.Field(Of String)("vType")
If (typeCounts.ContainsKey(type)) Then
typeCounts(type) += 1
Else
typeCounts.Add(type, 1)
End If
Next
Now you have a dictionary where the key is the type and the value is the count of the rows with this type.
why not getting the pretend result from the db itself?
Like so:
select count(*), vType
from someTable
group by vType
Not so sure about your question .. but this is what I've considered ..
You can make it as Sub ..
Sub AssignIncr(ByVal ds as DataSet,byval sFi as String,byval sCrit as String,ByRef Counter as Integer)
For each dr as dataRow in ds.rows
If dr(sFi) = sCrit Then Counter += 1
Next dr
End Sub
So you may use it by ..
AssignIncr(dsType,"vType","A",CountA)

Further problems with counting occurrences of strings in an Array

I am copying a question and answer from elsewhere as it partly goes into what I need but not completely.
In ASP classic, is there a way to count the number of times a string appears in an array of strings and output them based on string and occurrence count?
For example if I have an array which contains the following :
hello
happy
hello
hello
testing
hello
test
happy
The output would be:
hello 4
happy 2
test 1
testing 1
The answer that was given was this:
I'm assuming the language is VBScript (since that's what most people use with classic ASP).
You can use a Dictionary object to keep track of the individual counts:
Function CountValues(pArray)
Dim i, item
Dim dictCounts
Set dictCounts = Server.CreateObject("Scripting.Dictionary")
For i = LBound(pArray) To UBound(pArray)
item = pArray(i)
If Not dictCounts.Exists(item) Then
dictCounts.Add item, 0
End If
dictCounts.Item(item) = dictCounts.Item(item) + 1
Next
Set CountValues = dictCounts
End Function
This is great but I can't work out how to grab the top 2 most used words, display them and be able to put them in their own variable for use elsewhere.
Can anyone help with this?
You can loop through the dictionary object using this method. Inside that loop keep track of the top two keys and their counts in either a new array or two new variables.
You can't sort a Dictionary object in VBScript, so you have to use something else.
My advice is using a disconnected Recordset object to hold the items and their occurrences. Such object natively support sorting and it's pretty easy to use. To achieve this have such function instead:
Function CountValues_Recordset(pArray)
Dim i, item
Dim oRS
Const adVarChar = 200
Const adInteger = 3
Set oRS = CreateObject("ADODB.Recordset")
oRS.Fields.Append "Item", adVarChar, 255
oRS.Fields.Append "Occurrences", adInteger, 255
oRS.Open
For i = LBound(pArray) To UBound(pArray)
item = pArray(i)
oRS.Filter = "Item='" & Replace(item, "'", "''") & "'"
If (oRS.EOF) Then
oRS.AddNew
oRS.Fields("Item").Value = item
oRS.Fields("Occurrences").Value = 1
Else
oRS.Fields("Occurrences").Value = oRS.Fields("Occurrences").Value + 1
End If
oRS.Update
oRS.Filter = ""
Next
oRS.Sort = "Occurrences DESC"
oRS.MoveFirst
Set CountValues_Recordset = oRS
End Function
And using it to achieve the output you want:
Dim myArray, oRS
myArray = Array("happy", "hello", "hello", "testing", "hello", "test", "hello", "happy")
Set oRS = CountValues_Recordset(myArray)
Do Until oRS.EOF
Response.Write(oRS("item") & " " & oRS("Occurrences") & "<br />")
oRS.MoveNext
Loop
oRS.Close
Set oRS = Nothing
Don't forget to close and dispose the recordset after using it.

Resources