I have a form with a ComboBox and a button. when the button is clicked, it's event should check that ComboBox has a value before proceeding.
ComboBox has a default value set:
Name=cmbName,
Default Value = "Joe",
RowSource=SELECT name
FROM table
ORDER BY name;
This is what I tried:
Private Sub btnOk_Click()
If (CmbName.ListIndex = -1)Then
Exit Sub
End If
'Do Something
End Sub
But every time I click the button, cmbName.ListIndex does equal -1, and the sub is exited even though there is a default value.
Not sure if I'm misunderstanding something; you can just use the IsNull() function.
If the user has changed the value away from the default value, back to a null value, then this will return True.
Private Sub btnOk_Click()
If IsNull(CmbName.Value) Then
Exit Sub
End If
'Do Something
End Sub
ListIndex is a property of ComboBox. It returns the index of the chosen value in the list. For example: If the first value is selected, comboBox.listIndex = 0. If there is no value, then comboBox.listIndex = -1.
If the user doesn't select a value from the list, then the value is the default "joe".
If the query SELECT name
FROM table
ORDER BY name returns a list in which there is no value "joe", then listIdex will still be -1.
Try:
If (CmbName.ListIndex = -1) And (Trim(CmbName.Value & "") = "")
Will return true if no value was selected and the box is empty.
Related
My project has a DataGridView, in frmConsProd, where the ID column field, receives the prdCod column value from the SQL DB Table.
I need to pass two parameters to second form frmDetailProd when I click on the Consult button,tsbCons. The first parameter is the string "Consult", however, I'm having trouble sending the ID column value of the DataGridView as the second parameter.
Code:
Public Class frmConsProd
Private Sub tsbCons_Click(sender As Object, e As EventArgs) Handles tsbConsult.Click
Try
Using frm As New frmDetailProd("Consult", "datagrid ID value")
frm.txtPrdCod.Enabled = True
frm.txtPrdCod.Text = ""
frm.ShowDialog()
End Using
tsbRefresh.PerformClick()
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
End Class
How to get the ID value of my DataGridView, to be able to send it as a second parameter in the Consult button tsbCons?
If you are only after one value you can try this:
dim CellValue = yourGrid.Rows(0).Cells(4).value
This example would give you the value of first row, 5th column.
It worked
I created a string and assigned it the value of the datagrid column to be able to pass it as a parameter:
DIM codPrd As String = DataGridView.CurrentRow,Cells("prdCod").Value
I have a ComboBox in an excel userform that has two Columns the first is hidden and contains the staff employee number the second column contains the staff name.
I generate an email from a userform with which I include the staff name
Me.cbName.Column(1)
which works perfectly, except that this is an optional field so when no staff member is selected it returns an error as Column(1) doesn't exist.
I tried to create the following function to get the value and return it as a string but it returns the same error.
Public Function GetStaffName(cb As MSForms.ComboBox) As String
If IsError(cb.Column(1)) = True Then
GetStaffName = cb.Value
Else
GetStaffName = cb.Column(1)
End If
End Function
Has anyone got a work around to reference a combobox that may or may not have a column?
just check Combobox ListIndex property against `-1○6 to see if any selection is made:
Public Function GetStaffName(cb As MSForms.ComboBox) As String
If cb.ListIndex <> -1 Then GetStaffName = cb.Column(1)
End Function
if no selection is made then no action is taken so the function will return an empty string (which is the default value for a String variable)
I managed a crude work around.
Public Function GetStaffName(cb As MSForms.ComboBox) As String
On Error GoTo errhand:
GetStaffName = cb.Column(1)
Exit Function
errhand:
GetStaffName = ""
End Function
Like I said, crude. I'm sure there must be a better way. If someone manages to find a better solution I'll make it as correct.
Can you use the column count property is some way of the cb?
Sorry, I can't test but something like?
Public Function GetStaffName(cb As MSForms.ComboBox) As String
If not cb.ColumnCount = 2 then
GetStaffName = cb.Value
Else
GetStaffName = cb.Column(1)
End If
End Function
I'm having trouble adding dynamically a combo box column to my datagridview (before you ask, yes it must be dynamic and not done in editor).
The main feature is that the combobox cell is different for each row, so it must be done using combo box cell. checkedRows is a datatable.
Name of the datagridview is editCameraTable. It already has a few columns at this point:
'create new column
Dim resComboColumn As New DataGridViewComboBoxColumn _
With {.HeaderText = "Resolution", .ReadOnly = False, .DisplayIndex = 7, .Name = "Resolution", _
.DisplayMember = "Name", .ValueMember = "ID", .DataPropertyName = "ID"}
'add combo box column
EditCameras.editCameraTable.Columns.Insert(17, resComboColumn)
addResCmbBox(checkedRows, resComboColumn)
Pretty straight forward. You'll notice I have the value member, dataproperty name, etc. Here's the addResCmbBox definition:
Public Function addResCmbBox(ByRef DT As DataTable, column As DataGridViewComboBoxColumn)
Dim resolutions As String()
'for each camera
For i As Integer = 0 To DT.Rows.Count - 1
Dim camera As camera = convertDTtoCam(DT, i)
'get the resarray
Select Case DT.Rows(i).Item("Maker").ToString.ToLower
Case "acti"
resolutions = ACTi.GetResArray(camera)
Case Else
resolutions = ACTi.GetResArray(camera)
End Select
'add items to combobox list
Dim comboCell As New DataGridViewComboBoxCell
comboCell.DataSource = resolutions
For j As Integer = 0 To resolutions.Length - 1
'set to current resolution value
If resolutions(j).TrimStart("N") = camera.res Then
comboCell.Value = resolutions(j)
End If
Next
comboCell.DisplayMember = "Name"
comboCell.ValueMember = "ID"
EditCameras.editCameraTable("Resolution", i) = comboCell
Next
Return Nothing
End Function
camera is a structure. I have no problems until I get to the displayMember and value member problem, i.e. the last line starting with "editcameras.editcameratable...".
When doing so, the exception of "The Field Name does not exist" pops up. If I don't assign the displayMember and valueMember, I have no problems. But, I can't get the value selected in the comboBox (it comes back as Null). At runtime, the combobox column has the valuemember and display name as "ID" and "Name".
How can I bind this comboboxcell to the row so that I can later get it's selected value?
UPDATE:
I did as was commented, and created a struct/class that was meant to be the resolution property:
Public Class ResolutionStruct
Property Name As String
Property ID As String
End Class
And within the loop I create a list of this class, and assign the values to it:
Dim resolutionList As New List(Of ACTi.ResolutionStruct)
For j As Integer = 0 To resolutions.Length - 1
Dim resClass As New ACTi.ResolutionStruct
resClass.Name = resolutions(j)
resClass.ID = resolutions(j)
resolutionList.Add(resClass)
Next
'set combocell values
comboCell.DisplayMember = "Name"
comboCell.ValueMember = "ID"
comboCell.DataSource = resolutionList
EditCameras.editCameraTable("Resolution", i) = comboCell
However, the comboboxCell doesn't show any value when it drops down. So, now I've bound the values but it shows nothing. Is there anything else I should be doing so that I get both the holy combo of seeing the values I'm picking AND having them be bound to the data grid view? :D
UPDATE 2
So, mea culpa. I was adding the combobox cell to the wrong column!
So now, it is showing the values. I click a value, and try to grab the selected value as as string:
Dim cmbbox2 As DataGridViewComboBoxCell = editCameraTable("Resolution", i)
resolution(i) = cmbbox2.Selected.ToString()
But it still says it's a null value! Mid build I checked the combobox props. IN fact "selected" is a boolean as false. It has no value, says it has no items as well. Any ideas on why it says it is null?
UPDATE3:
I recently resorted a different column in the table, and the values from the combo box are cleared! I guess it's really never being attached/bound in the first place.
UPDATE4:
Fixed it!!
Apparently this line:
editCameraTable.Sort(editCameraTable.Columns("ID"), System.ComponentModel.ListSortDirection.Ascending)
Caused the table to freak out! I can now get the value (woohoo!)
Right, I'll try to explain this shortly:
DisplayMember and ValueMember are supposed to be set using properties. For example you create a class containing Name and ID
Public Class Test
Property Name as String
Property ID as String
End Class
Create a few of these objects and put them in a list. Set the list as the datasource to the combobox. Now you can access the DisplayMember and ValueMember as you have written it in your code. Value would be the ID and SelectedItem would be the entire class.
What you are doing now is that you are adding a list of strings to the combobox. A String does not contain the Property Name nor ID, so naturally you can't fetch them. See it like this:
To be able to use Value and/or DisplayMember you need to be able to fetch the Property by yourself. In this case:
resolutions(j).Name
or
resolutions(j).ID
This does not work.
But for example you would be able to do this:
resolutions(j).Length
So You would be able to do this, which would display the Length in the combobox:
Combobox.DisplayMember = "Length"
To currently get the value you would have to do:
Combobox.SelectedItem.ToString()
But since you have it in a combobox column My guess is that this won't cut it since you can't fetch the value from the DataGridView.
EDIT: You are still doing this right?
<DataGridView>.Item("Resolution", i) = comboCell
Otherwise you will have empty comboboxes.
EDIT2: No need to fetch value from Combobox, get it from Grid cell instead:
<DataGridView>.Item("Resolution", i).Value
When creating the columns don't forget to set a defaultvalue to the combobox, otherwise it might be Nothing:
comboCell.DisplayMember = "Name"
comboCell.ValueMember = "ID"
comboCell.Value = resolutions(0)
I use code such as this to clear out the values in several text boxes:
Private Sub RibbonButtonInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RibbonButtonInsert.Click
UpdateDataSource()
StudentsBindingSource.ResetBindings(True)
DatePickerDateOfBirth.Value = ""
RichEditBoxForeName.Focus()
StudentsBindingSource.AddNew()
End Sub
Because the date picker control did not clear out like the other controls did, I tried:
DatePickerDateOfBirth.Value = ""
but it does not clear out. Instead, I get an "InvalidCastException".
Can you show me what coding I need to properly clear out the value in this data picker?
Actually you are not clearing it out, you are assigning a string value to it. and as it is a Date type, the assignment is wrong.
the assigned value must be a Date format, you can do this:
DatePickerDateOfBirth.Value = Date.MinValue
later you can check and if the value is equal to MinValue, then the date is not set.
You cant set DateTimePicker Value to null or empty string it's value must be a date
but you can but a checkbox in datetimepicker using ShowCheckBox Property
and then use dateTimePicker.Checked = false dateTimePicker.Checked
Hi there
What is the correct way of assigning the selected index's value from a listbox to a variable? The user selects an item in a listbox and then the output changes depending on their selection.
I use:
variablename = listbox.text
in the listBox_SelectedIndexChanged event and this works.
When I use the button_click event I use:
variablename = listbox.selectedindex
But this does not work in the listbox_selectedindexchanged event.
Please could you let me know if it is okay to use it like I did above or if I will run into problems and why you cannot use the selectedindex method.
Thanks!
A. It sounds like your variable is a string, and yet you are trying to assign to it the value returned by the SelectedIndex Property, which is an integer.
B. If you are trying to retrieve the value of the item associated with the SelectedINdex of the Listbox, use the Index to return the Object itself (the listbox is a list of Objects, which are often, but not always, going to be strings).
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
'THIS retrieves the Object referenced by the SelectedIndex Property (Note that you can populate
'the list with types other than String, so it is not a guarantee that you will get a string
'return when using someone else's code!):
SelectedName = ListBox1.Items(ListBox1.SelectedIndex).ToString
MsgBox(SelectedName)
End Sub
THIS is a little more direct, using the SelectedItem Property:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
'This returns the SelectedItem more directly, by using the SelectedItem Property
'in the event handler for SelectedIndexChanged:
SelectedName = ListBox1.SelectedItem.ToString
MsgBox(SelectedName)
End Sub
Well it depends what you want to achieve from the listbox's selected item.
There are a couple of possible ways, let me try to explain some of these for your homework.
Suppose you have a data table with two columns, and their rows...
ID Title
_________________________
1 First item's title
2 Second item's title
3 Third item's title
And you bind this data table to your list box as,
ListBox1.DisplayMember = "ID";
ListBox1.ValueMember = "Title";
If user selects second item from the list box.
Now if you want to get the display value (Title) of the selected item, then you can do
string displayValue = ListBox1.Text; // displayValue = Second item's title
OR even this to get same results.
// displayValue = Second item's title
string displayValue = ListBox1.SelectedItem.ToString();
And to get the value member against the selected item, you need to do
string selectedValue = ListBox1.SelectedValue; // selectedValue = 2
Now there are situations when you want to allow user to select more than one item from the list box, so you then set
ListBox1.SelectionMode = SelectionMode.MultiSimple;
OR
ListBox1.SelectionMode = SelectionMode.MultiExtended;
Now suppose if user selects two items; second and third.
So you can get the display values by simply iterating through the SelectedItems
string displayValues = string.Empty;
foreach (object selection in ListBox1.SelectedItems)
{
displayValues += selection.ToString() + ",";
}
// so displayValues = Second item's title, Third item's title,
And if you want to get ID's instead of Title's then...
I am also looking through it, I will post if found.
I hope your understandings build.
Good Luck!