Add Textbox values in CheckedListBox( as items) using VB.net - vb.net

i'm using vb.net to make a UI that connects via RS232. the 1st output that i defined is some kinda list of products, that i defined to be showed in a textbox.
Now i need to add items to that checkedlistbox. Don't mind the full list , think as it was only 1 product .
Example, textbox1.text="apple", so i want add the item "apple" to the listbox.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
SerialPort1.Write("Products" & vbCr)
Dim separated = TextBox1.Text.Split(";")
CheckedListBox1.Items = separated.Text 'i know this is wrong :('
End Sub
i tried everything , but there's no similar question anywhere. and pls, tell me what i've done wrong in the post before downvote ! cumps

Items is readonly. You need to use Add or AddRange. Since you're creating an array already, change it to this.
Dim separated = TextBox1.Text.Split(";")
CheckedListBox1.Items.Clear()
CheckedListBox1.Items.AddRange(separated)

Related

Needing Assistance with vb.NET Application

I don't normally post on forums because I try to find information for myself, and ask as an absolute last resort. I've tried scouring the net for answers, but I'm only receiving about half of the answer I'm looking for.
I'm currently building an application that deals with state law. There's one combo box and one text box. One for the offense title, and one for the numerical code for that particular code section. So say if I select "Kidnapping", it prepopulates the text box below it with "11-5-77", for example.
The method I've been using for, oh, about the last hour now, is:
If AWOffenseTitle.Text = "Kidnapping" Then
AWCN.Text = "11-5-77"
ElseIf AWOffenseTitle.Text = "False Imprisonment" Then
AWCN.Text = "11-5-78"
With AWOffenseTitle being the combo box name, and AWCN being the text box name. While this has proved to work perfectly well so far, I'm sure you can imagine with hundreds of offense titles, this is going to take a ridiculously long time. Well, I finally found a spreadsheet with offense titles and their respective title codes. What I'm looking to do is create two text files within a folder in the local directory "Offenses". One with a vertical list of offenses, and one with a vertical list of offense code numbers that populate the same lines in each. What I'm looking to do is populate the combo box with the contents of text file one (which I can do already), but then selecting an offense title will read the second text file and display it's proper title code. That's what has me at a loss. I'm relatively well-versed with vb.NET, but I'm not an expert by any means.
I'm hoping someone here will be able to provide a code example and explain it to me line-by-line so I can gain a better understanding. I want to get more proficient with VB although it's not so popular anymore. I've been using VB since 6.0, but not on a regular basis. More on a sporadic project kind of basis.
I really appreciate any assistance anyone might be able to provide, and if you need more information, I'd be glad to answer any questions. I tried to be as thorough as I could.
Thank you in advance!
First, you need to retrieve your data. I demonstrated using an Sql Server database containing a table named Offenses with columns named OffenseTitle and OffenseCode. You will have to change this code to match your situation.
Private Function GetOffenseData() As DataTable
Dim dt As New DataTable
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("Select OffenseTitle, OffenseCode From Offenses;")
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Return dt
End Function
As the Form loads, set the properties of the ComboBox. DisplayMember matches the name of the title column and ValueMember is the name of the code column.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetOffenseData()
ComboBox1.DisplayMember = "OffenseTitle"
ComboBox1.ValueMember = "OffenseCode"
ComboBox1.DataSource = dt
End Sub
Then when the selected item in the combo changes, just set the .Text property of TextBox to the SelectedValue in the combo and your code appears.
Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
TextBox1.Text = ComboBox1.SelectedValue.ToString
End Sub
There are other ways to do this if your data source is other than a database. Please advise if you need additional help.
In addition to HardCode's comment and Mary's detailed answer, I can only add an answer that's somewhere in between them.
It might be the case, that the information is not taken from a database, but from another source, like a text/data file or a web service. So it might be useful to create an abstraction for the data source you actually use.
First, I create a class or struct that will hold the data for each combo box item.
Class Offense
Public ReadOnly Property Title As String
Public ReadOnly Property Code As String
Public Sub New(title As String, code As String)
Me.Title = title
Me.Code = code
End Sub
End Class
Next, you need a method that retrieves a list of offenses that you can bind to your combo box. It's entirely up to you how you fill/fetch the offenses list. I have simply hard coded your two values here.
Private Function GetOffenseData() As List(Of Offense)
Dim offenses As New List(Of Offense)
offenses.Add(New Offense("Kidnapping", "11-5-77"))
offenses.Add(New Offense("False Imprisonment", "11-5-78"))
Return offenses
End Function
At a certain moment (probably in your form's Load event handler), you need to initialize your combo box. Just like Mary did, I use data binding.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
AWOffenseTitle.DropDownStyle = ComboBoxStyle.DropDownList
AWCN.ReadOnly = True
AWOffenseTitle.DisplayMember = NameOf(Offense.Title)
AWOffenseTitle.ValueMember = NameOf(Offense.Code)
AWOffenseTitle.DataSource = GetOffenseData()
End Sub
Note that I use the NameOf operator to get the desired property names of the Offense class. If you ever decide to rename the properties of your Offense class, you will be able to easily detect where they are used, since the compiler will complain if your code still uses the wrong property names somewhere.
Finally, the app needs to react to combo box value changes, so that the text box will show the corresponding offense code. Mary used an event handler for the SelectionChangeCommitted event, but I use a handler for the SelectedIndexChanged event instead:
Private Sub AWOffenseTitle_SelectedIndexChanged(sender As Object, e As EventArgs) Handles AWOffenseTitle.SelectedIndexChanged
AWCN.Text = AWOffenseTitle.SelectedValue
End Sub
(Up to now, I was not aware of the SelectionChangeCommitted event of the ComboBox control. I will need to look into this event to see if it is actually a better choice for this scenario, but I found that the SelectedIndexChanged event does the job just fine, so for now I sticked with that event, since I am more familiar with it.)

How can I add values to a Telerik RadGridView column filter that are not (yet) represented in the datasource?

In a vb.net WinForms application, we have a RadGridView with filtering. We have a column of categories and some users will want to filter to see only rows with specific category. However, the only values represented in the filter popup are what are currently represented in the grid/datasource. Our users want to be able to select a category, even if it is not yet in the grid.
I have seen some mention of OnDistinctValueLoading as a solution online, but it seems I do not have that event on my RadGridView.
I think we're using a custom package for Telerik a coworker put in our nuget feed, but it says Telerik.WinForms 1.0.0. I'm in Vb.Net, .Net framework 4.5.
I was able to figure this out.
I could load the categories on form load with something like this:
Private Sub frmMyForm_Load(sender As Object, e As EventArgs) Handles Me.Load
'...
LoadAllCategoriesForFilter()
'...
End Sub
Private Sub LoadAllCategoriesForFilter()
Dim categories As List(Of String) = GetCategoriesList()
If categories IsNot Nothing And categories.Count > 0 Then
rgvMyRadGridView.Columns("colCategory").DistinctValues.Clear()
For Each category As String In categories
rgvMyRadGridView.Columns("colCategory").DistinctValues.Add(category)
Next
End If
End Sub

How to get certain column value from selected row to apply to filter?

I'm a complete beginner in VB.NET
I have a task to make a form on visual studio and part of it is to make a functional button for report on orders. On navgrid portion of the form I have master object orders list with order id and order date while in datagridview a child object orderslist with details about the order
I need a button that would give me a report on selected order.
I have made a report already and the code for button so far looks like this:
Private Sub BarButtonItem1_ItemClick_1(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
CR3.OpenReport("arpt_Sales_Orders", "FilterHere")
End Sub
if the FilterHere part is left empty, i get report on ALL the orders with their details.
I have been trying to look for how to filter out what i need but with little success.
I have also tried to look into how to get value from order list (navgrid on the right) but I'm starting to think this is not gonna bring any use. Nevertheless here are my attempts at this so far
Dim vOrderID = atbv_Sales_Orders.CurrentRow(colOrderID)
Dim data As Object = NavGridView.SelectedRow(colOrderID);
Help would be appreciated. I've been on this for hours with little success
EDIT:
To my understanding i need to add to filter section
OrderID = (OrderID value from selected order)
So the question probably stands as, how do i get that value?
Ok, I have finally found the answer myself. Posting it if someone would come across similiar issue.
First row sets event to fire on pressing the button. Next two are what i needed
Private Sub BarButtonItem1_ItemClick_1(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem1.ItemClick
Dim vOrderID As Integer = CInt(cOrderID.Text)
CR3.OpenReport("arpt_Sales_Orders", "OrderID = '" & vOrderID & "'")
End Sub
Works flawlessly for me

my program is not adding items to listbox and is freezing up

im trying to add a very large amount of items to list box and what i need it for is i'm using to add selected items to itextsharp table report im using filters in the table just to display either the sales person who handled the customer or the date at which the incident occurred (or Issue was reported with the product) my filter system is as follows i have 4 categories which is 4 listboxes customer name, customer code(named listBox1 i have not got around to changing it yet) species name, and the error type my filter is placed under the searchBtn_Click event my filter and item adding code is as follows:
Private Sub searchBtn_Click(sender As Object, e As EventArgs) Handles searchBtn.Click
For Each obj As contactObject In custList
For Each item As speciesObject In speciesList
'loadLists()
If Trim(fromDate.Value) < Trim(obj.eventDate) Then
If Trim(toDate.Value) > Trim(obj.eventDate) Then
If Trim(fromDate.Value) < Trim(item.compDate) Then
If Trim(toDate.Value) > Trim(item.compDate) Then
End If
If Not customerListBox.Items.Contains(obj.customerName) Then
customerListBox.Items.Add(obj.customerName)
End If
If Not ListBox1.Items.Contains(obj.customer) Then
ListBox1.Items.Add(obj.customer)
End If
If Not speciesListBox.Items.Contains(item.name) Then
If ListBox1.Items.Contains(item.customerCode) Then
speciesListBox.Items.Add(Trim(item.name).ToUpper)
End If
End If
If Not errorListBox.Items.Contains(obj.issue + " - " + obj.issueDescription) Then
errorListBox.Items.Add(Trim(obj.issue + " - " + obj.issueDescription).ToUpper)
End If
End If
End If
End If
Next
Next
countErrors()
End Sub
then i have the query which is set up to get the customer info from the database system
Dim SqlText As String = "SELECT DISTINCT QEE.[EventID] ,QEE.[EventDate] ,QEE.[Employee] ,QEE.[Communication] ,QEE.[OtherCommunication] ,QEE.[Issue] ,QEE.[IssueDescription] ,QEE.[IssueComments] ,QEE.[Resolution] ,QEE.[ResolutionComments] ,QEE.[SalesOrderNumber] ,QEE.[CustomerPO] ,QEE.[SOStatus] ,QEE.[Customer] ,QEE.[CustomerName] ,QEE.[SalesPersonName] ,QEE.[IsResolved] ,QEE.[IssueValue] ,QEE.[DateAndTimeAdded] ,DATEDIFF(day, SOR.ReqShipDate, QEE.[EventDate]) AS Elapsed, SOR.ReqShipDate FROM [QualityTracking].[dbo].[tblQualityEventEntry] QEE INNER JOIN SysproCompanyC.dbo.SorMaster SOR ON QEE.SalesOrderNumber = SOR.SalesOrder COLLATE Latin1_General_CI_AS ORDER BY EventDate ASC, CustomerName ASC, SalesOrderNumber ASC;"
I could not fit all code on here
if you could also just general things to help as well i am new to vb.net but for other information things i have tried :
*listbox.startUpdate/endUpdate
*changing querys
*changing the sorted property (Right now its set for false)
*the issue happens when i choose select all and then hit search the database is holding almost 2Mil items and i need to be able to get it to move once i get it work stop freezing i will be able to increase the speed i just cant figure out totally where the issue is i know the query could be better probably (if you have any suggestions please feel free i'm learning)
*but i also see alot of people having this issue with listbox as being kinda a broken down way of listing items
*i have tried researching it and people have said use something else i cant do that for listbox is committed
Assuming Windows Forms.
You program might not be responding because of too many records to add, and each time you add an item into the ListBox.Items collection, the UI is refreshed.
You may either SuspendLayout while adding the lines into your Listbox, and ResumeLayout afterwards.
Private Sub searchBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
customerListBox.SuspendLayout();
// Place your code to populate the ListBox control here...
customerListBox.ResumeLayout();
End sub
This shall avoid a lot of refreshes from occuring while adding the items one by one and allow the application to lighten the add of items, then you resume the layout so that it refreshes the controls to display adequate information to the screen.
OR
You may use the ListBox.Items.AddRange() method along with List.ToArray().
Private Sub searchBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim custList As List(Of ConstactObject) = loadYourCustomers();
customerListBox.Items.AddRange(custList.ToArray());
Dim speciesList As List(Of SpeciesObject) = loadYourSpecies();
speciesListBox.Items.AddRange(speciesList.ToArray());
End sub
OR ELSE
I recommend using a DataGridView and setting its DataSource property to your list of objects.
So, in order to have the correct data, you'll have to:
Drop two DataGridView on your Form
Rename both DataGridView to a meaningful name (e.g. custListDataGridView, speciesListDataGridview)
Drop two BindingSource on your Form
Rename both BindingSource to a meaningful name (e.g. custListBindingSource, speciesListBindingSource)
In the designer, set the DataGridView.DataSource property to your respective BindingSource (e.g. custListDataGridview.DataSource = custListBindingsource, speciesListDataGridView.DataSource = speciesListBindingSource)
In the backing code, that is, in your searchBtn.Click event, you may set both your binding sources DataSource property
Private Sub searchBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim custList As IList(Of ContactObject) = loadYourContactObjects();
custListBindingSource.DataSource = custList;
Dim speciesList As IList(Of SpeciesObject) = loadYourSpeciesObject();
speciesListBindingSource.DataSource = speciesList;
End Sub
And your information data should be listed automatically without you having to manually add each record.

Adding a default number of items to list box in Visual Basic

I'm working on a project for my Visual Basic class and need a nudge in the right direction. I'm not going to go into exactly what the program is supposed to do in the end because I'm not really at that point yet. The step I'm stuck on now is this.
We are supposed to have two list boxes, one for Ingredients (which I've named lstIngredients) and the second for the Recipe (lstRecipe), we are also supposed to have a text box labeled Quantity for the user to enter how many of the selected item to add to the Recipe list. For example, if the user selects "eggs" and types 3 for the quantity, "eggs" should appear 3 times in the Recipe list box. Also, if nothing is put into the quantity box, it is supposed to default to adding one of the selected item to the Recipe list box.
With the code I have written, I am able to add items to the Recipe list as long as I type something into the quantity text box, but I cannot get the program to just add one when nothing is typed into the text box. Here is the code I have so far.
Public Class Form1
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim i As Integer = lstIngredients.SelectedIndex
If txtQuantity.text= "" Then
lstRecipe.Items.Add(1)
End If
Dim intCount As Integer = 0
While intCount < txtQuantity.Text
lstRecipe.Items.Add(lstIngredients.Items(i))
intCount += 1
End While
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
lstRecipe.Items.Clear()
txtQuantity.Clear()
End Sub
Any help on this step would be greatly appreciated. I'm sure I'll probably have more questions as I get farther into the coding, but I will edit this question to include those when the time comes.
First, you'll need to convert the value in your Quantity text box to an integer. For that, you can use either Integer.Parse or Integer.TryParse. For instance:
Dim value As Integer = Integer.Parse(Quantity.Text)
Then you can use a For loop to add the same item that many times, for instance:
For x As Integer = 1 to value
lstRecipe.Items.Add(lstIngredients.Items(i))
Next