get value of selected item in second column... returning previous item - vb.net

I get that there are other questions like this, but for some reason nobody seems to have this problem. I'm trying to populate a 2 column listview that I create on load like this.
With lstShipMethods
.View = View.Details
.FullRowSelect = True
.HeaderStyle = ColumnHeaderStyle.None ' set to whatever you need
.Columns.Clear() ' make sure collumnscollection is empty
' Add 3 columns
.Columns.AddRange(New ColumnHeader() {New ColumnHeader(), New ColumnHeader()})
End With
lstShipMethods.Items.Add(New ListViewItem({"col1data", "col2data1"}))
lstShipMethods.Items.Add(New ListViewItem({"col1data", "col2data2"}))
It populates just fine, but when I try to get the data from the selected items column like this
Private Sub lstShipMethods_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstShipMethods.SelectedIndexChanged
Dim val As String = lstShipMethods.FocusedItem.SubItems(1).Text
MessageBox.Show(val)
End Sub
after the first click it will always show both values aka second column from row one and row two will be output in the MessageBox.

You can use the ItemSelectionChanged event instead.
Private Sub lstShipMethods_SelectedIndexChanged(sender As System.Object, e As ListViewItemSelectionChangedEventArgs) Handles lstShipMethods.ItemSelectionChanged
If e.IsSelected Then
Dim val As String = lstShipMethods.FocusedItem.SubItems(1).Text
MessageBox.Show(val)
End If
End Sub

Related

How to pass the 2nd selected row in datagridview to textbox?

How do i pass my 2nd selected row in datagridview to textboxt. I only know how to put the first data. How do i pass the 2nd selected to textbox?
Dim i As Integer
i = DataGridView2.SelectedRows(0).Index
Me.txtEmployeeID.Text = DataGridView2.Item(0, i).Value
you can use this code it worked for me
Dim test As String = DataGridView1.SelectedRows(0).Cells(2).Value.ToString
You need to only change the .cell(Here write the index value of the cell)
Then you can use the string value to fill up textbox
Try using the following:
Dim secondRow as integer = 0
Private Sub DataGridView2_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView2.CellClick
'assuming that by second selected row, you mean the row after the selected row
secondRow = e.RowIndex + 1
End Sub
Private Sub RowToTextBox()
Try
For i = 0 to DataGridView2.ColumnCount - 1
txtEmployeeID.Text &= DataGridView2.Item(i, secondRow)
Next
Catch ex as Exception
MsgBox("You have selected the final row")
End Try
End Sub
I don't think Me. is needed when referring to a textbox in the same form.
Since you don't know how many rows your user will select, I think looping thought the SelectedRows collection might work. I used the Name column because that is what I happened to have in my grid. Instead of a MessageBox you could add the values to a ListBox.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each GridRow As DataGridViewRow In DataGridView1.SelectedRows
MessageBox.Show($"Value is {GridRow.Cells("Name").Value}")
Next
End Sub

Hide rows if column contains particular text/ string

I have a datagridview wich I have no bound datasource too I also have a button and three rows in my datagridview. If my column named STATUS contains the word CLOSED I would like to hide that entire row but i dont want to delete it just hide it.
If anyone woyuld like to know I am ussing VB.net
How can I do this?
If you are using a bound datasource you want to capture the DataGridView.DataSourceChanged event.
Would look like this.
Private Sub DataGridView1_DataSourceChanged(sender As Object, e As System.EventArgs) Handles DataGridView1.DataSourceChanged
For Each row As DataGridViewRow In DirectCast(sender, DataGridView).Rows
If row.Cells("status").Value.ToString.ToLower.Contains("Closed") Then
row.Visible = False
End If
Next
End Sub
If you are not using a datasource you would want to capture the DataGridView.RowsAdded event.
Would look like this.
Private Sub DataGridView1_RowsAdded(sender As Object, e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles DataGridView1.RowsAdded
Dim dg As DataGridView = sender
If dg.Columns.Count > 0 And e.RowIndex <> 0 Then
Dim theRow As DataGridViewRow = dg.Rows(e.RowIndex)
If theRow.Cells("status").Value.ToString.ToLower.Contains("closed") Then
theRow.Visible = False
End If
End If
End Sub

VB.NET datagridview one-to-one mapping of combobox

I have a datagridview with two textbox columns and one combobox column. The combobox's DataSource is bound to enums for the values of the dropdown. The datagridview's DataSource is bound to a custom class with datatypes of string, string and enum.
The first two columns are pre-populated with values and in the third column the user must select a value from the dropdown. All this is working excellent so far except....
The combobox field should be a one-to-one kind of mapping, meaning no two comboboxes should have the same value. I am really not sure how to implement this kind of behavior. Should the chosen value be removed from the remaining dropdowns? should the chosen value remain in the dropdown and just give an error when two of the same are selected?
Any ideas and how to implement these ideas will be of great help.
Thanks
note the only acceptable value that can be used more than once is 'None'
I have an idea based off your intent to possibly remove the chosen value from the remaining dropdowns.
I have a class called Runner which has a similar setup to your example.
Public Class Runner
Public Property FirstName As String
Public Property LastName As String
Public Property Placement As Result
Public Sub New(fn As String, ln As String)
FirstName = fn
LastName = ln
Placement = Result.None
End Sub
End Class
I also have an enum called Result which will get populated into the ComboBoxCell:
Public Enum Result
None = 0
Bronze = 1
Silver = 2
Gold = 3
End Enum
When I create data objects and bind them to the DataGridView, I do so like this (note - Placements is a global List(Of Result) and Runners is a global List(Of Runner):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Placements.Add(Result.None)
Placements.Add(Result.Bronze)
Placements.Add(Result.Silver)
Placements.Add(Result.Gold)
Runners.Add(New Runner("John", "Smith"))
Runners.Add(New Runner("Jane", "Doe"))
Runners.Add(New Runner("Bill", "Jones"))
Column1.DataPropertyName = "FirstName"
Column2.DataPropertyName = "LastName"
Column3.DataPropertyName = "Placement"
Column3.DataSource = Placements
DataGridView1.DataSource = Runners
End Sub
Now, whenever the value of a cell in the ComboBoxColumn changes, you remove the new value from the list that contains the enums:
Private Sub DataGridView1_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
If (e.RowIndex > -1 And e.ColumnIndex = 2) Then
Dim currentvalue As Result = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
If currentvalue <> Result.None Then
Placements.Remove(currentvalue)
End If
End If
End Sub
Be careful when changing drop down selections... as per this Discussion, you have to trick the DataGridView into committing values as soon as the ComboBox value changes. I used an answer from that discussion and did something like this:
Private Sub DataGridView1_CurrentCellDirtyStateChanged(sender As Object, e As EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged
Dim col As DataGridViewColumn = DataGridView1.Columns(DataGridView1.CurrentCell.ColumnIndex)
If col.Name = "Column3" Then
DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
Dim selected As DataGridViewCell = DataGridView1.CurrentCell
DataGridView1.CurrentCell = Nothing //This line and the next one simply hide
DataGridView1.CurrentCell = selected //an odd display effect that occurs
//because we remove a value and change the
//selection at the same time
End If
End Sub
Finally, you want to handle the DataError event for the DataGridView and leave it blank so that you don't get Exceptions thrown at you when removing values from your list of enums.
This gets you about 90% of the way there. It will not re-add items to the list when you change a value. For example if I change from Gold to Silver, Gold should be added back to the list. You can probably figure out what events to handle to get the old value and the new one, and insert the old value back into the list at the correct index based on its enum value.
I decided to use the CellValidating event of the DataGridView to check whether or not the same value is selected more than once. If it is then a error message is displayed in the row header column.
The combobox in error will not lose focus until the error is resolved.
Private Sub DataGridView1_CellValidating(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellValidatingEventArgs) Handles DataGridView1.CellValidating
Dim headerText As String = DataGridView1.Columns(e.ColumnIndex).HeaderText
'Abort validation if cell is not in the Mapping column.
If Not headerText.Equals("Column Mapping") Then Return
'Clear error on current row.
DataGridView1.Rows(e.RowIndex).ErrorText = Nothing
e.Cancel = False
Dim newMappingValue As XmlElement = DirectCast([Enum].Parse(GetType(XmlElement), e.FormattedValue), XmlElement)
' Abort validation if cell value equal XmlElement.None
If newMappingValue.Equals(XmlElement.None) Then Return
For Each dgvRow As DataGridViewRow In DataGridView1.Rows
Dim currentMappingValue As XmlElement = dgvRow.Cells.Item(headerText).Value
If dgvRow.Index <> e.RowIndex Then
If currentMappingValue.Equals(newMappingValue) Then
DataGridView1.Rows(e.RowIndex).ErrorText = "Value already selected, please select a different value."
e.Cancel = True
End If
End If
Next
End Sub

How to copy One row to another row in gridview

Using VB.Net
I want to Copy one row data to another row.
I am using checkbox in the gridview, if i clicked the checkbox and press button then selected row copy to new cell (row)
Below code is working for delete, not working for copy the rows
Code
Private Sub btncopy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btncopy.Click
For Each m_row As System.Windows.Forms.DataGridViewRow In Me.grvList.Rows
If m_row.Cells("chksel").Value = True Then
Me.grvList.Rows.Add(m_row)
' Me.grvList.Rows.Remove(m_row)
End If
Next
End Sub
The above code is showing error as "Row provided already belongs to a DataGridView control."
What wrong with my code.
Need VB.Net Code Help
You can't add exactly the same row again. You will need to create a new row and populate it with the values from the row you are duplicating instead, then add the new row to the grvList.Rows
I am not sure what sorts of values you have in each cell, but as long as they are value types something like the following should work:
For Each m_row As System.Windows.Forms.DataGridViewRow In Me.grvList.Rows
If m_row.Cells("chksel").Value = True Then
'Create new row to hold duplicated values
Dim NewRow As DataRow = grvList.NewRow()
'loop thru existing rows to copy values
For i As Integer = 0 To m_row.Cells.Count - 1
NewRow(i) = m_row.Cells(i).Value
Next
'Add newly create row to table
Me.grvList.Rows.Add(NewRow)
' Me.grvList.Rows.Remove(m_row)
End If
Next
Keep in mind that if the items in any of the cells are reference types that you will still be referencing the same item, instead of creating a copy of the item. Much as you were doing by simply calling add on the same row you located.
Sorry, I missed that the rows were DataGridView rows, rather than a datatable that was bound... this should do the trick in that case:
For Each m_row As System.Windows.Forms.DataGridViewRow In Me.grvList.Rows
If m_row.Cells("chksel").Value = True Then
'Create new row to hold duplicated values
Dim NewRow As DataGridViewRow = m_row.Clone
'Add newly create row to table
Me.grvLIst.Rows.Add(NewRow)
End If
Next
'To copy Row
Private Sub CopyButton_Click(sender As System.Object, e As System.EventArgs) Handles CopyButton.Click
CopyRowIndex = DGV1.CurrentRow.Index
End Sub
'To Paste Row
Private Sub PasteButton_Click(sender As System.Object, e As System.EventArgs) Handles PasteButton.Click
PasteRowIndex = DGV1.CurrentRow.Index
For index As Int32 = 0 To DGV1.ColumnCount - 1
DGV1.Rows(CInt(PasteRowIndex)).Cells(index).Value = DGV1.Rows(CInt(CopyRowIndex)).Cells(index).Value
Next
End Sub
'To Duplicate Rows
Private Sub DuplicateButton_Click(sender As System.Object, e As System.EventArgs) Handles DuplicateButton.Click
CopyRowIndex = DGV1.CurrentRow.Index
DGV1.Rows.Add()
DuplicateRowIndex = DGV1.Rows.Count - 1
For index As Int32 = 0 To DGV1.ColumnCount - 1
DGV1.Rows(CInt(DuplicateRowIndex)).Cells(index).Value = DGV1.Rows(CInt(CopyRowIndex)).Cells(index).Value
Next
End Sub

Getting row number in a DataGridView

How do you get row number DataGridView cell? Specifically, if a user has selected a single cell, how can you get that row number? It needs to access a particular cell based on what the user has selected.
I know that the RemoveAt method can be used to remove at the Focus, but you cannot get the row number at focus apparently?
Thanks for the help!
You can simply use RowIndex on the current cell:
var row = dataGridView1.CurrentCell.RowIndex;
this one works fine .
Private Sub DataGridView1_RowPrePaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs) Handles DataGridView1.RowPrePaint
If e.RowIndex >= 0 Then
Me.DataGridView1.Rows(e.RowIndex).Cells(0).Value = e.RowIndex + 1
End If
End Sub
It is nearly the same but you may also use this solution:
var row = dataGridView1.CurrentRow.Index
Another way if you need to track user interaction with a DataGridView:
In my case there is extra processing in some generic functions that use the Me.I_SelCol and Me.I_SelRow column and row coordinates, but I haven't shown that because it's not relevant to the OP.
Best regards,
Rob
Private Sub I_DataGridView_CurrentCellChanged(sender As Object, e As EventArgs) Handles I_DataGridView.CurrentCellChanged
If Me.I_DataGridView.CurrentCellAddress.X < 0 Or Me.I_DataGridView.CurrentCellAddress.Y < 0 Then Exit Sub
' The Windows Me.I_DataGridView object will have already deselected the current cell and selected the
' new cell as per user navigation using mouse or cursor keys. We just need to store the current
' co-ordinates for the currently selected cell.
Me.I_SelCol = Me.I_DataGridView.CurrentCellAddress.X
Me.I_SelRow = Me.I_DataGridView.CurrentCellAddress.Y
Exit Sub
If you in event procedure of datagridview you will found "e As DataGridViewCellEventArgs" you can get row number with e.RowIndex and column number with e.ColumnIndex
Private Sub myDGV_CellLeave(sender As Object, e As DataGridViewCellEventArgs) Handles myDGV.CellLeave
Dim myRow As Integer = e.RowIndex
End Sub
And if you in normal procedure you can get row number like this:
Private Sub btnGetRow_Click(sender As Object, e As EventArgs) Handles btnGetRow.Click
dim myRow1 as Integer = 0
dim myRow2 as Integer = 0
myRow1 = myDGV.CurrentCell.RowIndex
myRow2 = myDGV.CurrentRow.Index
End Sub