How do I bind a data from a separate listbox? - vb.net

I have two listboxes and I have a button to display the selected item in a message box but I need to select from both listboxes. Is there a way for me to bind the data from the second listbox to the first one.
This is the interface:
This is how the data would be shown when selected
and what I meant by binding the data I want the 200 calory value to stay with rice even though something else is selected
Public Class Form1
Public strfood As String
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim calory As Single
strfood = InputBox("Enter food item", "Food List")
calory = InputBox("Enter calory", "Calory List")
FoodList.Items.Add(strfood)
CaloryList.Items.Add(calory)
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim selecteditem As String = FoodList.SelectedItems(0).ToString
Dim selectedcalory As String = CaloryList.SelectedItems(0).ToString
MessageBox.Show("Food :" + selecteditem & " " & "Calories :" + selectedcalory)
End Sub

Agree with djv's suggestion; these things should be in a single grid
right click the project in Solution Explorer
add new item
add a file of type DataSet
double click it, an empty surface appears. Rename the dataset to something sensible like CalTrackerDataSet (props grid)
right click the surface and choose Add..DataTable
name it Foods
right click the DataTable, choose Add..Column
name it Food
add another column named Calories, and set its type to Int32 (integer) in properties grid
save
go to your form
open the data sources tool panel (on the view menu, inside Other Windows) and find the Foods node, drag it into your form
an item appears in the bottom tray, called CalTrackerDataSet - change this to CalTrackerDS - I recommend this purely because it's a great point of confusion when vb names instances of things the same as the type
you don't need your BtnAdd code any more because new rows can be created just by typing into the grid, but if you did want to add a row like this, programmatically, you would:
Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Dim f = InputBox("Enter food item", "Food List")
Dim c = Convert.ToInt32(InputBox("Enter calory", "Calory List"))
CalTrackerDS.Foods.AddFoodsRow(f,c)
End Sub
And displaying the row the user clicked on is more subtle; a device called a BindingSource tracks the current row. Because it works with a wide range of data sources it returns quite basic objects that hide the specifics of the bound data so you have to cast to turn them back
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim cur and DirectCast(DirectCast(FoodsBindingSource.Current, DataRowView).Row, CalTrackerDataSet.FoodsRow)
MessageBox.Show("Food :" & cur.Food & " " & ", Calories :" & cur.Calories)
End Sub

Related

Why Serial number is vanished in DataGridView?

I am generating Auto Serial number in DataGridView using below code:
Public Class Form1
Dim table As New DataTable()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
table.Columns.Add("Sl", Type.GetType("System.Int32"))
table.Columns.Add("Id", Type.GetType("System.Int32"))
table.Columns.Add("Name", Type.GetType("System.String"))
table.Columns.Add("Amount", Type.GetType("System.Int32"))
DataGridView1.DataSource = table
DataGridView1.Columns(0).ReadOnly = True
DataGridView1.Columns(2).ReadOnly = True
End Sub
Private Sub DgvRowCountChanged()
For Each dgvr As DataGridViewRow In Me.DataGridView1.Rows
dgvr.Cells(0).Value = dgvr.Index + 1
Next
End Sub
Private Sub DataGridView1_RowsAdded(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles DataGridView1.RowsAdded
Me.DgvRowCountChanged()
End Sub
Private Sub DataGridView1_RowsRemoved(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowsRemovedEventArgs) Handles DataGridView1.RowsRemoved
Me.DgvRowCountChanged()
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim Index As Integer
If DataGridView1.RowCount > 1 Then
Index = DataGridView1.CurrentCell.RowIndex
DataGridView1.Rows.RemoveAt(Index)
End If
End Sub
End Class
Serial number appears, but when I click on next column it disappears. Why is that happening?
Do this, make life easy:
Ditch all that code
Make a new form
Add a new item of type DataSet to your project, and give it a nice name (not DataSet1)
Double click the dataset, so its design surface appears
Right click the surface, choose "Add new.. DataTable", give it a more imaginative name than DataTable1. I'll assume you choose License (serial number? name? seems licensey)
Right click the new datatable and choose "Add New.. Column"
Name the new column Sl, and use the properties grid to give it a type of System.Int32
Repeat for your other columns
Save
Open the Data Sources window on the View menu (Other Windows item)
Open the new blank form you made in step 2
Expand every node you can see in the Data Sources window
Drag the node representing your datatable (the one with an icon looking like a datagridview next toit) out of the data sources window and drop it on the form
Remove (delete) the bindingnavigator it created (you wont need it)
CLick the datagridview, CLick the small arrow that appeared in the top right of the control to show the popup menu, choose Edit Columns
Make whatever columns you want read only
Set other properties like sizes of columns, fill weights, header texts etc
Open the code of your form. add a single row of data to the datatable, in the constructor, after the initializecomponent() call:
Me.myImaginativeDataSetName.License.AddLicenseRow(1, 1, "Name Blah", 1234)
That's it. It looks like a lot because I've broken it down into the absolute step by step - about the only thing that isn't there is reminding you to take a breath every few steps because you'll be so blown away how easy it makes your life when you get the IDE to write code for you, ;)
OK, it's maybe not that exciting... But you already use the Forms designer to write reams of code for you, so this is how you leverage the other tools so you don't have to work with un-typed datasets all the time. Ugh.
The dataset this creates has a full suite of nicely named properties; don't use the basic stringy stuff ever again:
'yes - do this
For Each ro as LicenseRow in myDataSet.License
If ro.IsNameNull Then ro.Name = "Default Name" & ro.Sl
Next ro
'no - heck no
For Each ro as DataRow in myDataSet.Tables("License").Rows
If ro.IsNull("Naem") Then ro.item("Name") = "Default Name" & Convert.ToInt32(ro.Item("Sl"))
Next ro
See how much cleaner the first one is? ro.Sl is a nice Integer property, no casting or converting, no incessant Tables this or Columns/Rows that, Intellisense helps you out becaise it's all strongly named stuff, no typos in string column names like I made in the second...
It looks like youre trying to prevent the user from adding rows with this:
If DataGridView1.RowCount > 1 Then
Index = DataGridView1.CurrentCell.RowIndex
DataGridView1.Rows.RemoveAt(Index)
End If
End Sub
If so, click the datagridview on the form designer and in the properties grid set AllowUserToAddRows to false. If youre also trying to prevent deletion set the same on AllowUserToDeleteRows

vb.net ComboBox Text Changing When Left

I'm having an issue with my ComboBoxes whereby if I type into it to get a value & then tab out the Text changes to the first item in the list with the first letter typed.
I have:
AutoCompleteMode set to SuggestAppend
AutoCompleteSource set to ListItems
DropDownStyle set to DropDownList
I add the items for the ComboBox in the Load event of the Form the ComboBox is on.
e.g. the below is code from a Load event where I populate a ComboBox that I have set up as below.
`Me.ComboBox1.Text = ""
Me.ComboBox1.Items.Add("a")
Me.ComboBox1.Items.Add("aaa")
Me.ComboBox1.Items.Add("combo")
Me.ComboBox1.Items.Add("combobox")
Me.ComboBox1.Items.Add("combobox test")
Me.ComboBox1.Items.Add("common")
Me.ComboBox1.Items.Add("common dialog")`
After running the code, if I select the ComboBox1 & type in common - common is selected in ComboBox1 but if I leave ComboBox1 the Text reverts to combo.
It gets a bit stranger as if I user the below code in the ComboBox1_Leave event procedure it throws common:
MsgBox(ComboBox1.Text)
I've also tried assigning the value of Text to a string in the ComboBox1_KeyUp event procedure & then assign that to ComboBox1.Text in the ComboBox1_Leave event procedure but that doesn't do anything.
If I put a the above MsgBox code before assigning the strings value to ComboBox1.Text then the Text value does revert to Common but this is isn't a practical solution.
I've also noticed that if I hit Enter before hitting tab it retains the correct value but again I'm don't think this is a particularly practical solution.
Does anyone have any idea what's going on here & how I can fix it?
It is absolutely necessary to have the DropDownStyle set to DropDownList?
Because if you set DropDownStyle to DropDown the selected value will be retained when you press tab or lose the focus.
If it's absolutely necessary to have it that way, you could try this.
Public Class Form2
Dim selectedTextForCombo As String = ""
Private Sub Form2_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.ComboBox1.Text = ""
Me.ComboBox1.Items.Add("a")
Me.ComboBox1.Items.Add("aaa")
Me.ComboBox1.Items.Add("combo")
Me.ComboBox1.Items.Add("combobox")
Me.ComboBox1.Items.Add("combobox test")
Me.ComboBox1.Items.Add("common")
Me.ComboBox1.Items.Add("common dialog")
End Sub
Private Sub ComboBox1_LostFocus(sender As Object, e As System.EventArgs) Handles ComboBox1.LostFocus
ComboBox1.SelectedItem = selectedTextForCombo
'This is just for a visualization of your issue
'Label1.Text = selectedTextForCombo
End Sub
Private Sub ComboBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
selectedTextForCombo = ComboBox1.Text
'This is just for a visualization of your issue
'Label1.Text = selectedTextForCombo
End Sub
End Class
Warning:
This example works with the tab action.
If the users writes something that doesn't exist like "commun" the
selected value will end up being the visually selected value, in this
case: "common"

Trying to make smart combobox item interaction

I am here to find out is it possible to complete my idea to save me time writing long code.
I have 1 main combobox with various items and some other comboboxed. Each combobox of them is called "Combo" + the item from the main combobox.
and I wonder can I, when I click on an item to hide the last used combobox and to show the combobox linked to this item?
1. hide last used combobox
2. show the combobox responding to the selected item from the main combox
Public Sub ComboBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox2.SelectedIndexChanged
Dim SelectedAction As String = "Combo" + ComboBox2.Text
lastcombobox.visible = false
' now to assign to the new combobox
lastcombobox = (SelectedAction as name of combobox) combobox
Lastcombobox.visible = true
End Sub
Strings are not controls. Strings are the data type of Control.Name; that is the Name property of the control object. You cannot cast a string to a control but all is not lost. Create your other Combo Boxes at design time and stack them on top of each other. Notice the Static keyword before lastComboBox. This persists the value between calls to the method. You could accomplish the same thing by making this variable a class level variable. The first time the method is called their will be nothing in lastComboBox therefore the check for IsNothhing. Control.Find returns an array so we must refer to ctl(0) - the first element of the array, since we know it will return only one.
Private Sub Combo2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles Combo2.SelectedIndexChanged
Dim SelectedAction As String = "Combo" & Combo2.Text
Static lastComboBox As ComboBox
If Not IsNothing(lastComboBox) Then
lastComboBox.Visible = False
End If
Dim ctl() As Control = Controls.Find(SelectedAction, True)
lastComboBox = CType(ctl(0), ComboBox)
lastComboBox.BringToFront()
lastComboBox.Visible = True
End Sub

vb.net add values from listbox to textbox via drag&drop AND via double click

I'm struggling with some functionality I want to use on my Windows form.
( Just for info, this is for an AutoDesk Inventor AddIn. )
This is my form layout.
The current workflow
The top 4 list-boxes are filled with available parameter names. The user chooses the parameter(s) he/she wants to use and drags and drops it into one of the driving parameter text-boxes ( marked with the <1> label ).
The code that relates to the drag and drop operations
Private Sub lstTemp_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) _
Handles lbModelParameters.MouseDown,
lbUserParameters.MouseDown,
lbReferenceParameters.MouseDown,
lbLinkedParameters.MouseDown
' In order to access a specific item in a listbox.itemcollection, you must think of it
' as an array of data or a collection and access it in the same manner by always
' letting VB know which item you intend to use by identifying it with its index location
' within the collection. And this is better than taking up basket weaving :-)
lbModelParameters.DoDragDrop(sender.Items(sender.SelectedIndex()).ToString, DragDropEffects.Move)
End Sub
Private Sub txtTemp_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) _
Handles tbParameter1.DragEnter,
tbParameter2.DragEnter,
tbParameter3.DragEnter,
tbParameter4.DragEnter,
tbParameter5.DragEnter
'Check the format of the incoming data and accept it if the destination control is able to handle
' the data format
'Data verification
If e.Data().GetDataPresent(DataFormats.Text) Then
e.Effect() = DragDropEffects.Move
Else
e.Effect() = DragDropEffects.None
End If
End Sub
Private Sub txtTemp_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) _
Handles tbParameter1.DragDrop,
tbParameter2.DragDrop,
tbParameter3.DragDrop,
tbParameter4.DragDrop,
tbParameter5.DragDrop
'This procedure receives the dragged data once it passes the data verification handled by the DragEnter method
'Drops the data onto the destination control
sender.Text() = e.Data().GetData(DataFormats.Text).ToString()
End Sub
New functionality
Now I would like to decrease the user mouse movement for ergonomic reasons and speed. But I would also like to keep to the drag and drop functionality. As it can overwrite a value that has already been added by the user.
I would like to be able to DoubleClick a item in the listbox, and that item should be added to the first empty textbox. I named my textboxes with a number so it's easy to loop over them all to check if it's empty.
I tried doing it with this code, but my double click event never gets fired. It always goes to the drag and drop. How do you do handle this, that the double click gets fired instead of drag drop?
Private Sub ParameterAddDoubleClick(sender As Object, e As EventArgs) _
Handles lbModelParameters.DoubleClick,
lbUserParameters.DoubleClick,
lbReferenceParameters.DoubleClick,
lbLinkedParameters.DoubleClick
Dim oControl As Windows.Forms.ListBox
oControl = DirectCast(sender, Windows.Forms.ListBox)
' Add line in likedparameters listbox
If oControl.SelectedIndex <> -1 Then
' Loop trough all the controls to see if one is empty
' if it's empty add parameter, else go to next
' if all textboxes are used do nothing.
For i = 1 To 6
Dim oTextbox As Windows.Forms.TextBox =
CType(gbDrivingParameters.Controls("tbParameter" & i),
Windows.Forms.TextBox)
If oTextbox.TextLength = 0 Then
' Add the sender item into the linked listbox
oTextbox.Text = oControl.Items.Item(oControl.SelectedIndex)
End If
Next
End If
End Sub
I hope my question is clear, and well prepared. If there is additional information needed, please let me know in a comment.
Mousedown triggers the DoDragDrop, wich stops the doubleclick-event from firing.
To identify if a user doubleclicks or wants to perform a dragdrop, consider the following:
Private Sub ListBox1_MouseDown(sender As Object, e As MouseEventArgs) Handles ListBox1.MouseDown
' Determine whether we are performing a drag operation OR a double click
If e.Clicks = 1 Then
TextBox1.Text = "mousedown"
Else
TextBox1.Text = "dblclick"
End If
End Sub

Transfer data from one listview to another when data been double click

I have 2 ListView setup.
Listview1 need to pass the data to listview2 when any of the data is double click by user.
How can I archive this? I am using vb 2008.
here is the image :
This is crude and simple, but it will give you a starting point. Note that there are any number of ways to approach this problem, and you will want to figure out any validation and such as required by your application. The biggest hurdle appears to be grabbing a reference to the item which is the target of the double click (as important, making sure that if the user double-clicks in an empty area of the ListView Control, that the last selected item is not added by mistake.
Hope this helps:
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.ListView1.FullRowSelect = True
Me.ListView2.FullRowSelect = True
End Sub
Private Sub AddItemToSecondList(ByVal item As ListViewItem)
' NOTE: We separate this part into its own method so that
' items can be added to the second list by other means
' (such as an "Add to Purchase" button)
' ALSO NOTE: Depending on your requirements, you may want to
' add a check in your code here or elsewhere to prevent
' adding an item more than once.
Me.ListView2.Items.Add(item.Clone())
End Sub
Private Sub ListView1_MouseDoubleClick(sender As Object, e As System.Windows.Forms.MouseEventArgs) Handles ListView1.MouseDoubleClick
' Use the HitTest method to grab a reference to the item which was
' double-clicked. Note that if the user double-clicks in an empty
' area of the list, the HitTestInfo.Item will be Nothing (which is what
' what we would want to happen):
Dim info As ListViewHitTestInfo = Me.ListView1.HitTest(e.X, e.Y)
'Get a reference to the item:
Dim item As ListViewItem = info.Item
' Make sure an item was the trget of the double-click:
If Not item Is Nothing Then
Me.AddItemToSecondList(item)
End If
End Sub
End Class