Basic solution for adding list item to combo box via code on load - vb.net

What I need:
I was a basic equivalent of a select box i.e. a combobox of dropdown list style (that preferably doesn't allow text input).
I need to add the list items by code rather than the property box.
What I have:
Private Sub Form_Load ()
ComboStaffMember.AddItem "John Murphy"
End Sub
...produces "...add item is not a member of system.windows.forms.comboxbox".
Private Sub Form_Load ()
ComboStaffMember.Items.Add("John Murphy")
End Sub
...produces no result.
My question:
Why is the item not adding? The form name is FrmStaffLogIn and it's in Form1.vb. Should Form_Load correspond to either of these or is my code incorrect elsewhere?

Try to put combo add statement in following format in form load event :
Private Sub Form_Load ()
Me.ComboStaffMember.Items.Add(New DictionaryEntry("Text to be displayed", 1))
End Sub

Are you sure your code line ComboStaffMember.Items.Add("John Murphy") doesn't work? it should work just fine.
The Add() method On Item collection expects object parameter and string as well can be passed as argument to it. Like below [C# code sample]:
this.comboBox1.Items.AddRange(
new string[] {"SomeText","SomeOtherText","LastText"});
Also, you probably don't see any item cause you haven't set a default selected item. Just expand the dropdown and you will see the items. To set the default selected item
this.comboBox1.SelectedIndex = 0;

Working code:
Private Sub FrmIdentCust_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ComboStaffMember.Items.Add("John Murphy")
End Sub
I was missing (sender As Object, e As EventArgs) Handles MyBase.Load.

Related

How to access data from calling object in vb.net

I have a Window-Form 'caller' in vb.net containing a datagridview with a small overview table of certain objects, each with its own ID in the first column. Now, if a row is double clicked, i want to show a dialog 'edit', where one can edit many details of that row which i do not want in the overview table.
My approach is as follows: In the caller form i wrote this to call 'edit':
Private Sub dgdata_dbclick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dg_data.CellMouseDoubleClick
Dim f_edit As New edit
f_edit.ShowDialog(Me)
End Sub
That works fine.
However, in the called Form "edit" i need to check, which ID was selected and load this data from the database to edit it. I can access some data from the calling form 'caller' using e.g.
MsgBox(CType(Me.Owner, caller).Text)
to show the window title of 'caller'. However, i want to extract the currently selected ID in the datagridview or at least some variabhle containing it. In the caller form, this could be easily done by evaluating
dg_data.Item(0, selectedRow).Value.ToString
but i cannot access any relevant information in 'caller'. I have a public class with some global variables there but i cannot access them as well.
Probably my strategy to solve this problem is not the most clever approach? Basically, i want to open a very detailed edit window when someone clicks on a line in an overviewtable but simultaniously blocking the rest of the application as long as the edit window is open.
Thanks!
The idea is to pass the data to the second form. When you create an instance of the second form (my class is called Form2, yours is called edit) with the New keyword the Sub New is called on Form2.
Private Sub OpenEditDialog()
Dim f_edit As New Form2(32) '32 is the number you retrieve from your DataGridView
f_edit.ShowDialog(Me)
f_edit.Dispose()
End Sub
You pass the ID to Form2 and set a variable at Form level. You can then use the variable anywhere in Form2.
Public Class Form2
Private ID As Long
Public Sub New(SelectedID As Long)
InitializeComponent()
ID = SelectedID
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
MessageBox.Show(ID.ToString)
End Sub
End Class
You need to call InitializeComponent() so the controls will show up.
How do you usually get data into objects? You set a property or pass an argument to a method or constructor? Why should this be any different? Decide which you want to use and then write that code in your form. If it's required data, I would suggest a constructor. Just write this code in your form:
Public Sub New
and hit Enter. That will generate a little extra code automatically. You can then add a field to store the value, a parameter to the constructor and then assign the parameter to the field inside.
Thank you for pointing me to the correct route.
I solved it like this (which works fine and which is hopefully acceptable):
In the calling form:
Private Sub dgdata_dbclick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dg_data.CellMouseDoubleClick
Dim selectedRow As Integer = dg_data.CurrentCell.RowIndex
Dim f_edit As New edit
f_edit.edit(dg_data.Item(0, selectedRow).Value.ToString)
f_edit.ShowDialog(Me)
f_edit.Dispose()
End Sub
In the called form:
Public Sub edit(ByVal id As Long) 'Handles MyBase.Load
'Enter commands to prepare your form
End Sub

How to make this more efficient?

Private Sub btnOne_Click(sender As Object, e As EventArgs) Handles btnOne.Click
txtAnswer.AppendText(1)
End Sub
So this is my code (It's for 0 through to 9 and a dot for decimal points).
I'm working on calculator for an assignment, my question is, can I make this more efficient so I don't have a lot code doing the same thing?
I had considered setting up a function to read the contents of the buttons and add them to the textbox, but then the operation buttons and clear buttons would just add to the textbox instead of performing the code assigned to them.
you can create one method for the numeric buttons and add their value to the Tag Object. Then you can just reference the tag object to append to the text
Private Sub NumericButtons_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim btn As Button
btn = sender
txtAnswer.AppendText(btn.Tag)
End Sub
You could create a function just like that, but it should read the number from the sender's Text property, and only assign the number buttons to that function in the OnClick event.
The other buttons will have their own OnClick methods, and you should make a generic function like in this case when you find a common behavior in some of them. Perhaps you could do another generic function for all + - / x operators, it that's appropriate.

How to display Drop Down item TEXT from Menu Strip

What I Wish to achieve is to extract the select item text and display it into a messagebox (for start, then i'm going to use it for a SQL Query...)
I want to extract that particular selected ITEM, for instance : "SPR (Suivi piece rechange)" in the following image :
I tried this, but when I click on "Menu", it returns the name of my menu strip "MenuStrip1" :
Private Sub MenuStrip1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuStrip1.Click
MessageBox.Show(DirectCast(sender, MenuStrip).Name)
End Sub
EDIT:
I forgot to mention that all the ITEMS are added dynamically from the database,
so there will be no predefined Private Sub....End Sub Procedure for these Items.
Thanks in advance.
The MenuStrip object only refers to the actual menu strip itself, not the individual menu items, which are actually ToolStripMenuItem objects. You're looking for the Text property of those objects. For example:
DirectCast(YourDynamicMenuItemObjectHere, ToolStripMenuItem).Text
If you're looking for a way to capture events, you'll need to create a generic event handler:
Private Sub GenericMenuItem_Click(sender As System.Object, e As System.EventArgs)
MessageBox.Show(DirectCast(sender, ToolStripMenuItem).Text)
'Whatever else you need to do based on the text of the menu item
End Sub
And then hook that handler to the menu items whenever they're created:
'Code that creates YourDynamicallyGeneratedMenuItem
AddHandler YourDynamicallyGeneratedMenuItem.Click, AddressOf GenericMenuItem_Click

Edit Update DatagridView VB.Net (No Database)

Good day everyone.
I need your help in this project I am into (a Visual Basic program with no database.) It just contains a Datagridview, a Textbox, and three buttons (an "Add" Button, a "Edit" and an "Update" Button).
1 . Is there any way (like using "for loop") to automatically assign DataGridView1.Item("item location") to the one edited and be updated?
2 . Or is it possible to just click an item in the Datagridview then it will be edited at that without passing it to a Textbox, and to be updated at that.
The DataGridViewCellEventArgs variable (e in the method stub the designer will generate for you) of the double click event of the cell has RowIndex and ColumnIndex properties which refer to the position of the cell you clicked.
Save those (in a class variable possibly or a local one if that's all you need) and then refer to them when you update the cell in your DataGridView, possibly like this MyDataGridView.Item(e.ColumnIndex, e.RowIndex) or MyDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex) where e is the variable from the double click event handler.
For you cell double click event you could have something like this:
Private Sub DataGridView1_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
Using myEditor As New frmCellEditor(Me.DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value)
If myEditor.ShowDialog() = DialogResult.OK Then
Me.DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value = myEditor.NewCellValue
End If
End Using
End Sub
This will call a new instance of your editor and get a value from you. For the purpose of this demo I have made a form like this:
Public Class frmCellEditor
Public NewCellValue As Integer
Public Sub New(ByVal CurrentCellValue As Object)
InitializeComponent()
Me.TextBox1.Text = CStr(CurrentCellValue)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.NewCellValue = CInt(Me.TextBox1.Text)
Me.DialogResult = DialogResult.OK
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Call Me.Close()
End Sub
End Class
Which just has two buttons (Button1 = OK, Button2 = Cancel). When you click OK, it just returns the value 1 which then gets set as the value of the cell.
This is a VERY simplistic example, but it should provide you the basics of what you are trying to do.
UPDATE:
I updated the code for the editor interface so it will include handling for passing the value back and forth from the form with your datagridview.
In your project, make a new form called frmCellEditor. This forms has to have two buttons and a textbox (Make sure that the programmatic names match!). Replace the code with the code listed above. You will have to add Imports System.Windows.Forms above the class as well.
Amend the event handler for the cell double click event of your datagrid to pass the cell value when frmCellEditor is constructed (the line going ... New frmCellEditor(...).
How many columns does your DataGridView has?
Based on how you populate your DataGridView, I'll assume only 1.
Declare this on top of your form
Dim i as Integer
On your btnUpdate_Click Event (Just combine your Edit and Update button into One)
SELECT CASE btnUpdate.Text
Case "Update"
With DataGridView1
'Check if there is a selected row
If .SelectedRows.Count = 0 Then
Msgbox "No Row Selected for Update"
Exit Sub
End If
i = .CurrentRow.Index 'Remember the Row Position
Textbox1.Text = .item(0 ,i).value 'Pass the Value to the textbox
.Enabled = False 'Disable DataGridView to prevent users from clicking other row while updating.
btnUpdate.Text = "Save"
End With
Case Else 'Save
DatagridView1.Item(0,i).Value = Textbox1.Text
btnUpdate.Text = "Update"
END SELECT
Thanks for those who contributed to finding answers for this thread. I have not used your solutions for now (maybe some other time). After some research, I've found an answer for problem 2 (more user friendly at that):
2 . Or is it possible to just click an item in the Datagridview then
it will be edited at that without passing it to a Textbox, and to be
updated at that.
Here's what i did:
in Private Sub Form1_Load, just add:
yourDataGridView.EditMode = DataGridViewEditMode.EditOnEnter
in Private Sub yourDataGridView_(whatever event here: DoubleCellClick, CellContentClick, etc.) add:
DataGridView1(e.ColumnIndex, e.RowIndex).[ReadOnly] = False
DataGridView1.BeginEdit(False)

Value of global variable won't change

I have a variable whose scope needs to be global, because it needs to be called in a function as well as in a button press. So I declared the variable in a Module so it would be global.
The problem is that the value of this variable needs to be equal to the value of the text property of a textbox in the form.
Here you can download the VB.net demonstration of my problem: http://db.tt/DDxQJDXl
Below is an explanation of what happens
You enter a string into the textbox, in this case I entered "Hello". Then you click the button and it displays what you wrote.
You click OK in that message box and change the value in the textbox. In this case I changed it to "Goodbye". Then I hit the button again, but the variable did not change values and the messagebox displays "Hello" again.
Here is the entire source code:
Module Module1
Public strDataValue = frmTest.txtDataValue.Text
End Module
Public Class frmTest
Private Sub btnTest_Click(sender As System.Object, e As System.EventArgs) Handles btnTest.Click
MsgBox(strDataValue)
End Sub
End Class
Note: This is just a demonstration of a problem I'm having in a much larger program so the variable does have to be global.
You need to set the value of the field to the new value in the TextBox:
Private Sub btnTest_Click(sender As System.Object, e As System.EventArgs) Handles btnTest.Click
strDataValue = txtDataValue.Text
MsgBox(strDataValue)
End Sub
The field will not change values by itself.
The value of strDataValue won't automatically change when txtDataValue.Text changes. You need to update strDataValue manually, either when the textbox loses focus, or when you click the Test button.
You could also have a public property, which automatically returns the actual value as long as the form is open.
Public ReadOnly Property DataValue() As String
Get
Return frmTest.txtDataValue.Text
End Get
End Property
You need to assign value of txtDataValue.Text to your variable strDataValue in better performance
Using of Timer object or TextChenged event not recommended
Any change of txtDataValue.Text can assign after end of editing action
for me best solution: Leave or LostFocus events
Private Sub txtDataValue_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDataValue.Leave
strDataValue = txtDataValue.Text
End Sub