How to insert a conditional combobox? - vba

I'm working with VBA, and I'm struggling to get a combobox with two options:
First option: the textbox next to it must appear one "-", like if is supposed to be empty or disabled.
Second option: the same texbox must must be able to receive an input, like numbers.
Like: "Do you have an ID?" if no, don't fill the texbox. If yes, fill it with your number.
Thanks!

I'm assuming C# implementation but this would work essentially for any .net or WINFORMS project.
if(cbo.selectedindex = 0)
tbFoo.text = "-";
else if(cbo.selectedindex == 1)
tbFoo.text = "filltextwithID";
Check if the selectedindex of your combobox is the first or second options in the list and do your first option with the first selectedindex, else if it is the second, fill your textbox with whatever you need to fill it with(textwise).
Use your conditional if statement(naturally, I know) to check your conditions that you want your combobox to do to your textbox.
Otherwise another way to do this is with a selectedindexchanged event and do your switch statement or if statement based on which selectedindex you are talking about. 0 is the first item....all the way up to n items.

I got it! Here's the code:
Private Sub ComboBox_Change()
If ComboBox = "I don't have an ID" Then
IdTextBox.Visible = False 'Hidden
IdLabel.Visible = False
Else
IdTextBox.Visible = True 'Unhidden
IdLabel.Visible = True
End If
End Sub

Related

How can I get the checkbox.checked event to fire when I pass it as a parameter in vb.net?

I have programmed a long time but I’m relatively new to vb.net. And I’ve avoided subroutines and functions in which I passed parameters because I always get stuck. I’m trying to write a subroutine to pass information that will fill a TextBox or a checkbox with either the value from a table or clear the field or set to false. The first code below is an example of what I’ve been doing and this works. I trying to write a subroutine to pass 1.the name of the textbox or checkbox control on my form,2.the data row value, and 3.the column name in the table. The problem is when I passed a checkbox I can’t get the checked event to show on my control(CoreCol) that I passed. It knows it’s a checkbox and it will set the text of the checkbox too true or false but it won’t change the box checked.
This is an example of the old way that works. For a TextBox and a checkbox
' A Machine
If Not IsDBNull(r("A Machine")) Or Not IsNothing(r("A Machine")) Then
TbXMachA.Text = r("A Machine")
Else
TbXMachA.Text = ""
End If
If Not IsDBNull(r("A CO2 Box?")) Or Not IsNothing(r("A CO2 Box?")) Then
CkbxCO2BoxA.Checked = r("A CO2 Box?")
Else
CkbxCO2BoxA.Checked = False
End If
This works
LoadData2TextBox(Me. TbXMachA, r, "A Machine ")
This doesn’t
LoadData2TextBox(Me.CkbxCO2BoxA, r, "A CO2 Box?")
this is the sub routine I'm writing
Private Sub LoadData2TextBox(ByRef CoreCol As Control, CoreRow As DataRow, BoxStage As String)
If Not IsDBNull(CoreRow(BoxStage)) Then
If TypeOf CoreCol Is TextBox Then
CoreCol.Text = CoreRow(BoxStage)
End If
If TypeOf CoreCol Is CheckBox Then
CoreCol.??? = CoreRow(BoxStage)
End If
Else
CoreCol.Text = ""
End If
You know that CoreCol is a CheckBox so you can cast it as one then use it as a CheckBox.
If TypeOf CoreCol Is CheckBox Then
Dim myCheckBox = DirectCast(CoreCol, CheckBox)
myCheckBox.Checked = DirectCast(CoreRow(BoxStage), Boolean)
End If
Another cast in getting the boolean value out of CoreRow(BoxStage). The above code assumes this will work, but I am not sure what is in CoreRow(BoxStage). You may need to add some logic based on the value depending on what it is. For example:
myCheckBox.Checked = CoreRow(BoxStage) = "somevalue"

For a combobox, selectedIndex returns 0 while selectedtext returns a value

Once I select a value from a Combobox and save the form, ComboBox.SelectedText contains the value selected but ComboBox.SelectedIndex is returning 0 always for each item in the list. Below is just a sample code for reference.
If (combobox1.SelectedIndex = 0 Or combobox1.SelectedText = "")
MessageBox.Show("No value selected")
else
MessageBox.Show("Some value selected")
End If
Some code to illustrate usage
Private Sub ComboBox1_SelectedIndexChanged(sender As Object,
e As EventArgs) Handles ComboBox1.SelectedIndexChanged
'check for no item selected
If ComboBox1.SelectedIndex < 0 Then
Stop 'no item
Else
Dim idx As Integer = ComboBox1.SelectedIndex
Dim val As String = CStr(ComboBox1.SelectedItem) '<-- use SelectedItem
Stop
End If
End Sub
Small Answer
SelectedText is not the same as SelectedItem. Take a look at ComboBox.SelectedText:
Gets or sets the text that is selected in the editable portion of a ComboBox.
I think that you are confusing this with ComboBox.SelectedItem
SelectedIndex: -1 if nothing selected, otherwise the index of the selected item
SelectedValue: null if nothing selected, otherwise the selected item
SelectedText: the text that the operator marked in the editable part of the combo box.
** Room for improvement **
You use VB. My VB is a bit rusty, so I'll give my answer in C#. I guess you'll get the gist.
In Winforms, whenever you want to fill a that shows a sequence of items, like ComboBoxes, ListBoxes, DataGridViews, Charts, etc, there are usually two methods:
Fill the ComboBox one by one with the texts that you want to display
Use a DataSource: fill it with the Items that you want to be selectable, and tell the ComboBox which property of the selectable items you want to display.
Use the first method if you only want to display a constant array of strings. Fill ComboBox.Items. When an item is selected, use SelectedIndex to get the index of the selected string. Use ComboBox.Items[selectedIndex] to get the selected string.
If the string represents something more than just a string, for instance the text represents a Customer, or a Product. It is usually easier to use the DataSource method.
To do that, you use property ComboBox.DataSource to tell the ComboBox which Customersit should display. In ComboBox.ValueMember you tell the ComboBox which Customer poperty should be used to represent the Customer, for instance the name of the Customer.
Once the operator selected the name of the Customer, you get the complete Selected Customer using property ComboBox.SelectedItem:
List<Customer> availableCustomers = ...
ComboBox combo1 = new ComboBox(...);
combo1.ValueMember = nameof(Customer.Name); // the Customer property that you want to display
combo1.DataSource = availableCustomers;
After the operator selected an item, you can process the event, and fetch the selected customer immediately:
Customer selectedCustomer = (Customer)cmbo1.SelectedValue;
ProcessSelectedCustomer(selectedCustomer);
Of course you should only select a property that is unique. If you have two Customers named "Hans Brinker", operators wouldn't know which name represents which Customer.
Apart from the nice thing that you don't have to do a lookup from SelectedIndex to what this selected item represents (a Customer), you are independent of the order in which the Customers are displayed.
Another nice thing: if in future versions you want to change from ComboBox to ListBox, or maybe even to DataGridView, you won't have to change your model drastically: the control still shows a sequence of Customers, and once an operator selects something that represents this Customer (Name? Id?, DataGridView Row?), you get the complete Customer.
(1)ComboBox1.SelectedIndex starts from -1, when you are not selected, ComboBox1.SelectedIndex=-1
(2)When you click combobox1.items, SelectedText is always "".
This is because, at the time of these events(SelectedIndexChanged, SelectedValueChanged.. ), the previous SelectedText value has been cleared and the new value has not yet been set. You can use the SelectedItem property instead.
E.g:combobox1.SelectedItem
Please try the following code.
If ComboBox1.SelectedIndex = -1 Then
MessageBox.Show("No value selected")
Else
MessageBox.Show("Some value selected")
End If

if combo box selected item is null how do I assign an empty string to it instead? vb.net

I have a property called ReplacementTo
and I set a value to it based on the selecteditem from the combobox, like this:
classEquipmentItem.ReplacementTo = cmbReplcmnt.SelectedItem.ToString
Now I can't use cmbReplcmnt.Text because what I actually need is the value of that SelectedItem
So problem is, if the user leaves the combobox as blank, it throws a null exception.
I decided to use the IIf function then:
classEquipmentItem.ReplacementTo = IIf(IsNothing(cmbReplcmnt.SelectedItem.ToString), classEquipmentItem.ReplacementTo = "", cmbReplcmnt.SelectedItem.ToString)
Unfortunately I still get the error
I tried using a Try-Catch for it and it worked, but I don't want to rely on the Try-Catch, so I was wondering is there a another way to work this through?
You can try SelectedValue instead of SelectedItem property.
IF IsNothing(cmbReplcmnt.SelectedItem) Then
classEquipmentItem.ReplacementTo=String.Empty
Else
classEquipmentItem.ReplacementTo=cmbReplcmnt.SelectedItem.ToString
'OR
'classEquipmentItem.ReplacementTo=cmbReplcmnt.SelectedValue.ToString
End If
Or, you can use IF or IIF
classEquipmentItem.ReplacementTo=IF(IsNothing(cmbReplcmnt.SelectedItem),
String.Empty,cmbReplcmnt.SelectedValue.ToString())
Your problem is IsNothing(cmbReplcmnt.SelectedItem.ToString)
The .ToString can't be evaluated in the case where the SelectedItem is Nothing so the IsNothing function fails
Your fixed code should be as follows:
classEquipmentItem.ReplacementTo = If(IsNothing(cmbReplcmnt.SelectedItem), "", cmbReplcmnt.SelectedItem.ToString)
Even easier than that though is this:
classEquipmentItem.ReplacementTo = CStr(cmbReplcmnt.SelectedItem)

How do I set a VB.Net ComboBox default value

I can not locate the correct method to make the first item in a combo box visible.
The app starts with an empty combo box. The user makes a radio box selection then clicks Go! (how original). The combo box is loaded via an LDAP query. All this is working just fine. The problem is the combo box still appears to the user to be empty. They must click the arrow to see the options.
How do I make the first option 'visible' after the users clicks Go!?
' Your code filling the combobox '
...
If myComboBox.Items.Count > 0 Then
myComboBox.SelectedIndex = 0 ' The first item has index 0 '
End If
Just go to the combo box properties - DropDownStyle and change it to "DropDownList"
This will make visible the first item.
OR
you can write this down in your program
Private Sub ComboBoxExp_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)Handles MyBase.Load
AlarmHourSelect.Text = "YOUR DEFAULT VALUE"
AlarmMinuteSelect.Text = "YOUR DEFAULT VALUE"
End Sub
so when you start your program, the first thing it would do is set it on your assigned default value and later you can easily select your required option from the drop down list.
also keeping the DropDownStyle to DropDownList would make it look more cooler.
-Starkternate
because you have set index is 0 it shows always 1st value from combobox as input.
Try this :
With Me.ComboBox1
.DropDownStyle = ComboBoxStyle.DropDown
.Text = " "
End With
You can try this:
Me.cbo1.Text = Me.Cbo1.Items(0).Tostring
If ComboBox1.SelectedIndex = -1 Then
ComboBox1.SelectedIndex = 0
End If
Much simpler solution, Select the Combo-box, and in the option of Selected item, select the item index (0 for the first item) and set it to be the default value in the combo box.
Another good method for setting a DropDownList style combobox:
Combox1.SelectedIndex = Combox1.FindStringExact("test1")

How to switch between DataGridViewTextBoxCell and DataGridViewComboBoxCell?

I want to have a DataGridView that has two columns. The first column will always be of type DataGridViewComboBoxColumn. Based on the selection in that column, I'd like to be able to change the corresponding cell in the second column to either a DataGridViewComboBoxCell or a DataGridViewTextBoxCell.
I'm thinking I just need to make the second column of type DataGridViewColumn, but don't understand the mechanics of how to change the cell type on the fly.
I'm working with VB.NET in Visual Studio 2005.
Thanks in advance!
Update: One way around it, I suppose, is to make the second column as a DataGridViewComboBoxColumn, and change the attributes of the cell so that it either behaves like a drop-down list, or as an (editable) drop-down with no elements. The latter looks enough like a text box that I could live with it, and it wouldn't involve changing the type of the cell.
I don't have the VB.Net version,but hopefully this quick C# snippet will help you or point you in the right direction.
In this example, I set up a simple DataGridView with 2 columns. The first being a DataGridViewComboBox populated with two choices: "Text" or "Combo".
The second column is initially set to DataGridViewTextBoxColumn from the designer.
I handle the CurrentCellDirtyStateChanged event on the DataGridView. I check if the cell is dirty and only check the first column (The ComboBox). You gotta call the CommitEdit to get the new value in the combo or else you will be looking at the previous value. Based on the selection in the combo box I then overwrite the cell in the 2nd column with a new cell of that type.
You would add your own logic (populate the drop downs and handle the value). You might want to store the value and then put it back into the cell or whatever.
Here is the code I used and did a quick and dirty test on:
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty == false)
{
return;
}
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
if (dataGridView1.CurrentCell.ColumnIndex == 0)
{
if (((string)dataGridView1.CurrentCell.Value) == "Text")
{
dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1] = new DataGridViewTextBoxCell();
}
else if (((string)dataGridView1.CurrentCell.Value) == "Combo")
{
dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1] = new DataGridViewComboBoxCell();
}
}
}
Here is a quick VB translation, that I tested and works.
Public Class Form1
Private Sub DataGridView1_CurrentCellDirtyStateChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged
If DataGridView1.IsCurrentCellDirty = False Then
Return
End If
DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
If DataGridView1.CurrentCell.ColumnIndex = 0 Then
If CStr(DataGridView1.CurrentCell.Value) = "Text" Then
DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).Cells(1) = New DataGridViewTextBoxCell
ElseIf CStr(DataGridView1.CurrentCell.Value) = "Combo" Then
DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).Cells(1) = New DataGridViewComboBoxCell
End If
End If
End Sub
End Class
You will lose any value stored in that column, so you would need to save it first.
Jon
You can create your own cell template that hosts a user control. In the user control you add a textbox and a combobox, and add a method/property to show one and hide another.
This sample creates a radio button cell, it is not hard to change the code to host a user control.
dgvCell = new DataGridViewTextBoxCell(); // code to remove checkbox
dgvCell.Value = string.Empty;
dgv_modi_del_trans.Rows[1].Cells[0] = dgvCell;