How to get Design > Name property of DGV column from Header Text property - vb.net

I am trying to go through un-checked items within a CheckedListBox1 and based on the values returned hide relevant columns within DataGridView1 but the issue is that the values displayed in CheckedListBox1 are the HeaderText property of DGV column and not the Name property which is required for hiding the column within DGV.
See below code:
For Each checked_item As Object In CheckedListBox1.Items
If Not CheckedListBox1.CheckedItems.Contains(checked_item) Then
DataGridView1.Columns("").Visible = False
End If
Next
Is there a way to retrieve "Name" property of DGV column when referencing the column's HeaderText property?

You don't need the column name to hide the column. You need the column. The name is just a means to get the column. The issue is the way you're populating your CheckedListBox. Displaying the HeaderText makes perfect sense, because that's what the user actually sees. What you should be doing is putting the columns themselves into the CheckedListBox and just displaying the HeaderText. That way, the items are the columns, e.g.
Dim columns = DataGridView1.Columns.Cast(Of DataGridViewColumn)().ToArray()
With CheckedListBox1
.DataSource = columns
.DisplayMember = NameOf(DataGridViewColumn.HeaderText)
End With
The code you posted then becomes this:
For i = 0 To CheckedListBox1.Items.Count - 1
Dim column = DirectCast(CheckedListBox1.Items(i), DataGridViewColumn)
column.Visible = CheckedListBox1.GetItemChecked(i)
Next
Note that you should generally set the DataSource last when binding but that doesn't seem to work with a CheckedListBox, which doesn't offically support data-binding. For that reason, the DataSource is set first.
EDIT:
I'm adding this after the comment was added to the question about the ItemCheck event and the checking of the items at startup. The key here is to not actually act on the event until the list has been initialised, i.e. all the items have been initially checked. One way to do that would be like so:
Private isLoaded As Boolean = False
Private Sub Form1_Load(...) Handles MyBase.Load
'Bind the data and check the items in the CheckedListBox here.
isLoaded = True
End Sub
Private Sub CheckedListBox1_ItemCheck(...) CheckedListBox1.ItemCheck
If isLoaded Then
'Act here.
End If
End Sub
The other way to is to prevent event being raised by not handling it while the initialisation is taking place. That can be done in a couple of ways but I'll leave that to you as an exercise if that's what you want to do.
As the ItemCheck event is raised before the state of an item changes, you will need to treat the current item differently to the other items. My loop above would become this:
For i = 0 To CheckedListBox1.Items.Count - 1
Dim column = DirectCast(CheckedListBox1.Items(i), DataGridViewColumn)
'For the item that is being checked/unchecked, use its new state.
'For other items, use their current state.
column.Visible = If(i = e.Index,
e.NewValue = CheckState.Checked,
CheckedListBox1.GetItemChecked(i))
Next
That said, if all items are initially checked and all columns are initially visible, it's only the current item that you need to care about, so there's no need for a loop at all:
Dim column = DirectCast(CheckedListBox1.Items(e.Index), DataGridViewColumn)
column.Visible = (e.NewValue = CheckState.Checked)

Try this:
For Each checked_item As Object In CheckedListBox1.Items
Dim oCol As DataGridViewColumn = DataGridView1.Columns _
.Cast(Of DataGridViewColumn)() _
.Where(Function(x) x.HeaderText = checked_item).SingleOrDefault()
If oCol IsNot Nothing Then oCol.Visible = _
Not CheckedListBox1.CheckedItems.Contains(checked_item)
Next
Note: System.Linq is required!
[EDIT]
this code is executed in the .ItemCheck event. When the form starts up
I loop through all available columns, populate CheckedBoxList1 and as
default they are un-checked but I want them checked as I want the
columns to be visible at start
If you would like to change the visibility of column of currently selected item in CheckListBox (in ItemCheck event), use this:
Dim oCol As DataGridViewColumn = DataGridView1.Columns _
.Cast(Of DataGridViewColumn)() _
.Where(Function(x) x.HeaderText = checked_item).SingleOrDefault()
If oCol IsNot Nothing Then oCol.Visible = _
Not CheckedListBox1.CheckedItems.Contains(CheckedListBox1.SelectedItem)
Do you see the difference?
The main difference is: there's no foreach loop ;)

Related

Making One Column of DataGridView AutoComplete for String Data

I am trying to set up a DataGridView in VB.Net where a single column, called "Supplier" acts as a TextBox with an AutoCompleteSource to help users with entering data. This is the code I put together to attempt to accomplish this:
Private Sub OrderData_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) Handles orderData.EditingControlShowing
Dim colIndex = orderData.SelectedCells.Item(0).ColumnIndex
Dim headerText As String = orderData.Columns(colIndex).HeaderText
If headerText.Equals("Supplier") Then
Dim autoText As TextBox = TryCast(e.Control, TextBox)
If autoText IsNot Nothing Then
autoText.AutoCompleteMode = AutoCompleteMode.SuggestAppend
autoText.AutoCompleteSource = AutoCompleteSource.CustomSource
autoText.AutoCompleteCustomSource = FillTextBoxData("supplier_name", "suppliers")
End If
End If
End Sub
I kind of works. Unfortunately it adds AutoCompletes to every single editable column in the table, instead of just the "Supplier" column (column index 2).
What do I need to do to fix this?
EDIT: I modified the code a bit to try and fix the issue, and it kind of worked. If I don't selected the "Supplier" column first, then the other columns to not contain an AutoComplete. However if I go from the "Supplier" column to another column, then it contains an AutoComplete. How do I fix this?
When you do
Dim headerText As String = orderData.Columns(2).HeaderText
If headerText.Equals("Supplier") Then
That will be always true, since you are always getting the col 2 header no matter what cell is selected, you need to add that, something like
Dim colIndex = orderData.SelectedCells.Item(0).ColumnIndex
then you can use your code
Dim headerText As String = orderData.Columns(colIndex).HeaderText
Also add an Else clause to the If headerText.Equals("Supplier") Then statement. In the Else portion add the line autoText.AutoCompleteMode = AutoCompleteMode.None

Trying to move items from one to the other

]I am having strange problem when i try to move items from one grid view to another using a bindingsource it adding in an extra blank row some reason
Private Sub btnMove_Click(sender As System.Object, e As System.EventArgs) Handles btnMove.Click
Dim bs As New BindingSource
Dim a As Integer
Dim removeList As List(Of infoRemoteFiles) = fileList
For a = 0 To grdAvailFiles.SelectedRows.Count
grdProcessFiles.Rows.Add(grdAvailFiles.Rows(a).Cells("filename").Value)
removeList.RemoveAll(Function(p As infoRemoteFiles) p.filename = grdAvailFiles.Rows(a).Cells("filename").Value)
Next
bs.DataSource = removeList
grdAvailFiles.DataSource = bs
End Sub
please see what i mean its the row below what I have selected I dont no where its comming from thanks
The extra blank row is added automatically if you have the AllowUserToAddRows property set to True on the DataGridView control.
From the documentation:
If the DataGridView is bound to data, the user is allowed to add rows if both this property and the data source's IBindingList.AllowNew property are set to true.
On a separate note, you shouldn't have to create anew binding source (for the source data grid). Instead, modify the collection that is already bound to the DataSource property.
Try:
For A = 0 To grdAvailFiles.SelectedRows.Count - 1
Note the minus 1, because you're starting from zero.

Unable to set valuemember/display member to bind combobox

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)

VB.NET Iterating Form Labels

I have several label boxes on my design form that all share the naming convention lbl_#.text where # ranges from 1 to 60. I want to make a loop that iterates through each lbl_#.text adding some incremental value, let's say multiples of 2 for this question's theoretical purpose.
Something such that the end result would amount to the following:
lbl_1.text = "2"
lbl_2.text = "4"
lbl_3.text = "6"
...
lbl_60.text = "120"
I'm not sure how to access each of these labels through the coding side, I only know how to explicitly mention each label and assign a value :/
There are a few options here.
In this situation the labels will often have a common container, such as panel or groupbox control. In that case:
Dim formLabels = myContainerControl.Controls.OfType(Of Label)()
For Each formLabel As Label In formLabels
'...
Next formLabel
Of course, this mixes logical groups with visual groupings. Those two things don't always align well, so you can also...
Add them all to a Label array (or List(Of Label) or any other enumerable):
Dim formLabels(60) As Label = {lbl_1, lbl_2, lbl_3 .... }
For Each formLabel As Label in formLabels
'...
Next formLabel
But sometimes that's more trouble than it's worth, even if you use a loop to create the collection, and so you can also
Use the .Name property (in conjunction with a naming convention to identify your desired controls):
Dim formLabels = Controls.Where(Function(c) c.Name.StartsWith("lbl_"))
For Each formLabel As Label In formLabels
'...
Next formLabel
Some combination of the above (for example, code in the form load event to create a list based on the name property).
Notice the actual For Each loop is exactly the same in all of those options. No matter what you do, get to the point where you can write a single expression to identify the label control, and then run a simple loop over the expression result.
This points to a final strategy: think in terms of binding to a data source. With a data source, your labels are created as part of a DataGridView, FlowLayoutPanel, or similar control. Then you can iterate the rows in the grid or panel.
Use the Controls collection:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim i As Integer
For i = 1 To 3
Dim myLabel As Label = CType(Me.Controls("lbl_" & i), Label)
myLabel.Text = ...whatever value you want to put here
Next
End Sub
End Class
If you don't know how many labels there are, one option is to use a Do Loop.
Dim lblTarget As Label = Nothing
Dim intCursor As Integer = 1
Dim bolFirstIteration As Boolean = True
Do Until lblTarget Is Nothing AndAlso Not bolFirstIteration
If bolFirstIteration Then
bolFirstIteration = False
End If
lblTarget = CType(Me.Controls("lbl_" & intCursor.ToString()), Label)
If Not lblTarget Is Nothing Then
lblTarget.Text = (intCursor * 2).ToString()
End If
intCursor += 1
Loop

Error trying to rebind DataSource to DataGridViewComboBoxCell?

I have a DataGridView with two DataGridViewComboBoxColumns. I want to use the selected item in the first column to trigger a re-population of the items in the second column, on a per-row basis.
Here's the code I have so far. "addlInfoParentCat" identifies the first column, and currentRow.Cells.Item(1) is the DataGridViewComboBoxCell that I want to re-populate. ExtEventAdditionalInfoType is a type I defined that contains the string/value pairs.
Private Sub dgvAdditionalInfo_CellValueChanged(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgvAdditionalInfo.CellValueChanged
Dim currentCell As DataGridViewCell
currentCell = Me.dgvAdditionalInfo.CurrentCell
If Not currentCell Is Nothing Then
If currentCell.OwningColumn.DataPropertyName = "addlInfoParentCat" Then
Dim parentTypeID As Integer = currentCell.Value
Dim currentRow As DataGridViewRow = Me.dgvAdditionalInfo.CurrentRow
Dim subtypeCell As DataGridViewComboBoxCell = currentRow.Cells.Item(1)
Dim theChildren As New List(Of ExtEventAdditionalInfoType)
theChildren = Custom_ExtEventAdditionalInfoType.GetChildrenOfThisParentOrderByTypeName(parentTypeID)
subtypeCell.DataSource = Nothing
subtypeCell.DataSource = theChildren
subtypeCell.DisplayMember = "ExtEventAdditionalInfoTypeDescr"
subtypeCell.ValueMember = "ID_ExtEventAdditionalInfoType"
End If
End If
End Sub
Basically what I see is that the binding works great the first time around. When I select a item in the first column, it populates the items correctly in the second. I can add rows to the DataGridView and repeat the process.
The problem comes when I try to change the first-column item after the second column has already been bound. I get an endless string of dialog boxes with the following:
System.ArgumentException: DataGridViewComboBoxCell value is not valid.
Any idea why this is happening? Thanks in advance!
UPDATE CodeByMoonlight's suggestion appears to work.
I clear the DataGridViewComboBoxCell's value before re-binding:
....
subtypeCell.DataSource = Nothing
subtypeCell.Value = Nothing 'here's the change
subtypeCell.DataSource = theChildren
....
Well, it looks like as soon as you remodify the first combo's value, you're invalidating the binding and datasource you used to populate the second combo, causing all the errors.