Values from database based on two combo boxes into text box - sql

I am trying to put a value based on two cascading combo boxes from a database table into a text box. Filling the two cascading combo boxes works. However when I try to put the result in the text box I run into trouble. I am using the following code :
Private Sub CmbPlaasnaam_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CmbPlaasnaam.SelectedIndexChanged
If CmbAliasnaam.SelectedIndex > -1 AndAlso CmbPlaasnaam.SelectedIndex > -1 Then
Dim aliasnaam As String =
CmbAliasnaam.Items(CmbAliasnaam.SelectedIndex).ToString
Dim plaasnaam As String =
CmbPlaasnaam.Items(CmbPlaasnaam.SelectedIndex).ToString
Dim qry = From zc As SkeduleringsDatabasis6DataSet.OesskattingsRow In SkeduleringsDatabasis6DataSet.Oesskattings
Where zc.Aliasnaam = aliasnaam AndAlso
zc.Plaasnaam = plaasnaam
Select zc.Plaasnommer
txtPlaasnommer.Text = zc.plaasnommer
End If
End Sub

Use this line :
txtPlaasnommer.Text = qry.FirstOrDefault.ToString()

zc on your last line does not exists
you should use qry variable
like:
if qry.Count>0 Then
txtPlaasnommer.Text = qry.first
End If
zc is the inner linq variable and qry is the result that you should use

Related

how to add multiple selected items from CheckedListBox to SQL table in Visual Basic (VS2019)

I currently have the following that allows me to select whats in my CheckedListBox and it displays in a message box popup
public Sub CheckedListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles CheckedListBox1.SelectedIndexChanged
If CheckedListBox1.Items.Count > 0 Then
Dim Items As New List(Of String)
For Index As Int32 = 0 To (CheckedListBox1.Items.Count - 1)
If CheckedListBox1.GetItemChecked(Index) Then
Items.Add(CStr(CheckedListBox1.Items.Item(Index)))
End If
Next
Dim Result = String.Join(",", Items.ToArray)
'MessageBox.Show(Result)
Else
' Nothing checked
End If
Now i need that result set to be loaded to the parameter defined from my stored procedure :
' Add Multiple selections to Brand column in SQL.
sqlCommand.Parameters.Add(New SqlParameter("#SKU", SqlDbType.VarChar, 100))
sqlCommand.Parameters("#SKU").Value = CheckedListBox1.Text
Works fine with one selected value only.
but I am needing it to load the Dim Result into the #SKU parameter.
assuming example: sqlCommand.Parameters("#SKU").Value = (Result)
Regards
I figured it out. I allowed the Result set to load into a Label1:
Dim Result = String.Join(",", Items.ToArray)
Label1.Text = Result
Then I used the Label1.text to send through a variable to my stored proc:
sqlCommand.Parameters.Add(New SqlParameter("#SKU", SqlDbType.VarChar,100))
sqlCommand.Parameters("#SKU").Value = Label1.Text

Read data from dynamically created text-box

I'm trying to collect data after creating dynamic text-box with vb.net
Private Sub btn_OK_lines_number_Click(sender As Object, e As EventArgs)
Handles btn_OK_lines_number.Click
Dim i As Integer
Dim x As Integer
Dim Z As Integer
Z = 150
If IsNumeric(txt_lines_number.Text) Then
Int32.TryParse(txt_lines_number.Text, x)
For i = 1 To x
Dim newTB As New TextBox
Dim newLB As New Label
newLB.Name = "lbl_workstation_number_line" & i
newLB.Text = "Nbr Work Station in Line" & i
newLB.Size = New Size(190, 20)
newLB.ForeColor = Color.White
newLB.Font = New Font("consolas", 12, FontStyle.Regular, GraphicsUnit.Pixel)
newLB.Location = New Point(20, Z + i * 30)
newTB.Name = "Textbox" & i
newTB.Size = New Size(170, 20)
newTB.Location = New Point(200, Z + i * 30)
Me.Controls.Add(newTB)
Me.Controls.Add(newLB)
Next
i = i + 1
Else
MessageBox.Show("please enter a number")
txt_lines_number.Text = ""
End If
End Sub
Let's say you just have one row, and only create one TextBox. You set the name here:
newTB.Name = "Textbox" & i
where the resulting TextBox is named Textbox1. The problem is you can't just reference the identifier Textbox1 directly in your code, as you do with txt_lines_number. You can't even reference it as a member of the class (Me.Textbox1). This name didn't exist at compile time, and so it's not an identifier you can use, and it's not a member of the class at all. There was never a matching Dim statement for that name.
What you can do, though, is look again in the Controls collection where you added the TextBox to the form:
Me.Controls("Textbox1")
or
Me.Controls("Textbox1").Text
You may also need to cast the value to a TextBox:
Dim box As TextBox = DirectCast(Me.Controls("Textbox1"), TextBox)
MessageBox.Show(box.Text)
Remember that case matters here.
Further saving this in a DB is out of scope for one question. There are as many ways to do that as there are programmers in the world. You should make your own attempt first, and come back here with a new question when you run into specific problems.
Thank you,
this is my attempt and it is done !
Dim userInput As TextBox = Form1.Controls.Item("TextBox" & i.ToString)
mycommand.Parameters.AddWithValue("#workstation", userInput.Text)
:D
Because you creating dynamic amount of input controls, right tool for the job will be DataGridView control.
Create a class to represent your data
Public Class LineInfo
Public Property Number As Integer
Public Property WorkStationNumber As Integer
End Class
Create `DataGridView in the form designer.
Private Sub btn_OK_lines_number_Click(sender As Object, e As EventArgs) Handles btn_OK_lines_number.Click
Dim linesAmount As Integer
If Integer.TryParse(txt_lines_number.Text, linesAmount) = False Then
MessageBox.Show("please enter a number")
txt_lines_number.Text = ""
Exit Sub
End If
' Create class instance for every line
Dim lines =
Enumerable.Range(1, linesAmount)
.Select(Function(i) New LineInfo With { .Number = i })
.ToList()
'Set lines as DataSource to the DataGridView
Me.DataGridView1.DataSource = lines
End Sub
DataGridView will display all lines and provide input fields to update work station numbers.
You can access updated lines later by casting DataSource back to the List
Dim lines = DirectCast(Me.DataGridView1.DataSource, List(Of LineInfo))
' Now you can access all data and save it to the database
Dim parameters =
lines.Select(Function(line)
Return new SqlParameter With
{
.ParameterName = $"#workstation{line.Number}",
.SqlDbType = SqlDbType.Int,
.Value = line.WorkStationNumber
}
End Function)
.ToList()
myCommand.Parameters.AddRange(parameters)
You can freely change style, font colors of different columns in the datagridview.

Split string into Sub String

I Am Using Vb.net. My idea is when I paste (ctrl+v) for example this character :
AHAKAPATARAE
I Have 6 textboxes.
it would automatically paste them in textboxes one by one in order!
so
txtBox1 will contain : AH
txtBox2 : AK
txtBox3 : AP
txtBox4 : AT
texbox5 : AR
texbox6 : AE
The automation of inserting Licence Keys will ease so much
so that user will not work so hard to cut & paste each two digits!
so any suggestion of doing auto-fill inside textboxes..?
Thanks.
This will allow the paste into the first textbox, as well as move forward correctly if the user types the whole thing manually starting in the first box:
Private Sub txtBox1_TextChanged(sender As Object, e As EventArgs) Handles txtBox6.TextChanged, txtBox5.TextChanged, txtBox4.TextChanged, txtBox3.TextChanged, txtBox2.TextChanged, txtBox1.TextChanged
Dim TB As TextBox = DirectCast(sender, TextBox)
Dim value As String = TB.Text
If value.Length > 2 Then
TB.Text = value.Substring(0, 2)
Dim TBs() As TextBox = {txtBox1, txtBox2, txtBox3, txtBox4, txtBox5, txtBox6}
Dim index As Integer = Array.IndexOf(TBs, TB)
If index > -1 AndAlso index < (TBs.Length - 1) Then
index = index + 1
TBs(index).Text = value.Substring(2)
TBs(index).Focus()
TBs(index).SelectionStart = TBs(index).TextLength
End If
End If
End Sub
There are definitely many more ways this could be accomplished...
Handle the key down event on textbox 1
Private Sub txtBox1_KeyDown(sender As Object, e As System.Windows.Forms.KeyEventArgs) Handles txtBox1.KeyDown
If e.Modifiers = Keys.Control AndAlso e.KeyCode = Keys.V Then
' Get Clipboard Text
Dim cpText as String = My.Computer.Clipboard.GetText()
' Assign
txtBox1.Text = cpText.Substring(0, 2)
txtBox2.Text = cpText.Substring(2, 2)
txtBox3.Text = cpText.Substring(4, 2)
txtBox4.Text = cpText.Substring(6, 2)
txtBox5.Text = cpText.Substring(8, 2)
txtBox6.Text = cpText.Substring(10, 2)
'the event has been handled manually
e.Handled = True
End If
End Sub
Another option is to have one masked textbox event. Might be easier

JOIN the Strings of different textboxes and again SPLIT

I am new in vb.net, so not much familiar with all VB functions. While working on 1 Windows Application, while taking order we need to save product and its specification like weight, height, width, color, length, material etc.
since every product can have different specification so its is not possible to determine and provide for fields in database.
So, I decided to provide textboxes so user can enter name & value while entering product details. 1 textbox for name & other textbox for value.
like this
Textbox1 = "WEIGHT" TextBox2 = "10" '(Value of Weight)
Textbox3 = "WIDTH" TextBox4 = "5" '(value of Width)
Textbox4 = "LENGTH" TextBox5 = "5" '(Value of Length)
(All these textboxes are dynamically created in Groupbox "GBox1")
Instead of saving product specification in separate column. I want to save these names & values as String e.g. "WEIGHT=10;WIDTH=5;LENGTH=5" in SQL Database(TEXT OR VARCHAR field). Because we dnt want any calculations or search etc. on this. just customer requirements to book order & save in Database for future records.
Then again While calling or editing Product SPLIT the string as separate fields, String Before = Separate & string after = separate, then display all names & their corresponding values in Textboxes (as Displayed while adding) so user can edit and after changes again save as single string value.
After search I found SPLIT & JOIN functions for this purpose.
need some help in using these functions in Loop to merge string from textboxes
for each loop to read all textboxes in Groupbox
Dim ItemList As New ArrayList()
Dim PrDetails As String
For Each Ctrl As Control In GBox1.Controls
If TypeOf Ctrl Is TextBox Then
ItemList.Add(CType(Ctrl, TextBox).Text)
End If
Next
PrDetails = String.Join()
How to perform join on these array list? and again SPLIT this pattern while retrieving from Database.
Also need suggestions regarding this approach or any other way to implement. Thanks.
For this solution to work, you will need to accept the fact that there needs to be some amount of standardization to your solution. TextBox1 and TextBox3 won't work as names, so I used txtName1 and txtValue1 etc. To test this solution, make a new form, put GroupBox1, paste the code in the class and run.
Private nameTextBoxName = "txtName" ' name textbox prefix
Private valueTextBoxName = "txtValue" ' value textbox prefix
Private paramSeparator = ";" ' between sets of parameters
Private nameAndValueSeparator = "=" ' between name and value
Private xOffset = 10 ' for horizontal spacing inside the groupbox
Private yOffset = 20 ' for vertical spacing inside the groupbox
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' your example data
Dim testString = "WEIGHT=10;WIDTH=5;LENGTH=5"
' set the textboxes
setTextBoxes(testString)
' get the string from the textboxes
Dim result = getTextBoxesString()
End Sub
' call to get a string with all the data from the textboxes
Private Function getTextBoxesString() As String
Dim stringToDatabase = ""
Dim textBoxes = GroupBox1.Controls.OfType(Of Control).
Where(Function(co As Control) TypeOf co Is TextBox).
Select(Of TextBox)(Function(co As Control) CType(co, TextBox))
Dim nameTextBoxes = textBoxes.Where(Function(co As Control) co.Name.Contains(nameTextBoxName))
Dim valueTextBoxes = textBoxes.Where(Function(co As Control) co.Name.Contains(valueTextBoxName))
stringToDatabase = nameTextBoxes.Select(Of String)(
Function(nameTextBox As TextBox)
Dim valueTextBox = valueTextBoxes.
Where(Function(vtb As TextBox) vtb.Name = nameTextBox.Name.Replace(nameTextBoxName, valueTextBoxName)).
First()
Return nameTextBox.Text & nameAndValueSeparator & valueTextBox.Text
End Function).Aggregate(Function(oldValue, newValue) oldValue & paramSeparator & newValue)
Return stringToDatabase
End Function
' call to set the textboxes inside the groupbox based on the data string
Private Sub setTextBoxes(textBoxesString As String)
Dim params = textBoxesString.Split(paramSeparator)
Dim index = 1
GroupBox1.Controls.Clear()
For Each param In params
Dim nameAndValue = param.Split(nameAndValueSeparator)
Dim nameTextBox As New TextBox With
{.Name = nameTextBoxName & index.ToString(),
.Text = nameAndValue(0),
.Location = New Point(xOffset, (index - 1) * .Height + yOffset)}
Dim valueTextBox As New TextBox With
{.Name = valueTextBoxName & index.ToString(),
.Text = nameAndValue(1),
.Location = New Point(.Width + xOffset, (index - 1) * .Height + yOffset)}
GroupBox1.Controls.Add(nameTextBox)
GroupBox1.Controls.Add(valueTextBox)
index += 1
Next
End Sub

Adding all entries to combobox in linq to sql

All i want to do is add each entry of my specific database table to a combo box on form load. This is what i have so far.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dc = New DataworldDataContext.DataworldDataContext
Dim countStates = (From z In dc.tblstates Select z).Count
Dim listStates = (From z In dc.tblstates Select z).ToList
For i = 0 To countStates - 1
cmbDealerState.Items.Add(listStates)
i = i + 1
Next
End Sub
Im getting the error "Items collection cannot be modified when the DataSource property is set." How can i fix this
For your 2nd problem, the combo box will have 2 properties called DisplayMember and ValueMember. The display one is the text you wish to display and the value the (usually numeric) value you return when an item is selected. Simply set them:
cmbDealerState.DisplayMember = "myDisplay"
cmbDealerState.ValueMember = "myValue"
I am presuming you are using WinForms here. If its WPF then its a bit more tricky.
Edit
dc = New DataworldDataContext.DataworldDataContext
Dim countStates = (From z In dc.tblstates Select z.StateCode).Count
Dim listStates = (From z In dc.tblstates Select z.StateCode).ToList
cmbDealerState.DisplayMember = "StateCode"
cmbDealerState.ValueMember = "StateCode"
This still gives me nothing
The problem you have is that you are trying to set DisplayMember and ValueMember to be a ToString representation of your list. In your database you will have columns that identify the data name, for example
StateID StateName
1 New York
2 Washington
The values you need to set therefore would be:
cmbDealerState.DisplayMember = "StateName"
cmbDealerState.ValueMember = "StateID"
Obviously these names are made up, but you get the idea.
When I tried this (in C#) I needed to access cmbDealerState.SelectedItem to get the values that had been selected.
Still Nothing
dc = New DataworldDataContext.DataworldDataContext
Dim listStates = (From z In dc.tblstates Select z.StateCode).ToList()
cmbDealerState.DataSource = listStates
This worked