dgv add row number to headercell - vb.net

I'm trying to show the rownumber of a datagridview in the headercell I was under the impression that this was possible but I can't get it to show the value.
What do I need to do?
** The dgv is bound with BindingSource **
My attempt:
Private Sub NumberRows()
For Each oRow As DataGridViewRow In dgvBodyOverview.Rows
oRow.HeaderCell.Value = (oRow.Index + 1).ToString
Next
End Sub

To reproduce your problem, I followed your comment:
I'm calling it from a sub that loads all rows and at the end the call is made.
Doing this, the numbers failed to show whether or not the grid had a DataSource. Instead, I've typically done this as Plutonix suggested above - in DataGridView.CellFormatting.
Private Sub dataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs)
Dim header As DataGridViewRowHeaderCell = Me.dataGridView1.Rows(e.RowIndex).HeaderCell
If e.ColumnIndex = 0 Then
header.Value = [String].Format("{0}", e.RowIndex + 1)
End If
End Sub
I check for ColumnIndex = 0 to ensure the header cell value is only set once per row. See this C# answer for additional explanation.

Related

filling datagridview from an array

How can I fill a datagridview from an array or a list.
I have the following line that get the like in a datagridview from a textbox and adds it to an array, and I want to fill a datagridview with these values. how can I do that.
Private Sub TextBox4_TextChanged(sender As Object, e As EventArgs) Handles TextBox4.TextChanged
Dim match As DataGridViewCell() = (From row As DataGridViewRow In Me.DataGridView2.Rows From cell As DataGridViewCell In row.Cells Select cell Where CStr(cell.FormattedValue).Contains(Me.TextBox4.Text)).ToArray()
DataGridView2.DataSource = match.ToList()
end sub
tried this and it didnt work...
As I understand, here you me humble example to do that. But remember that we have an array which consists of five element "Arr(5)" with some values, then add these values in a specific DGV column, so please do the appropriate modification for your exact need.
Here is the code:
Public Class Form1
Private Sub BtnFillDGVFromArray_Click(sender As Object, e As EventArgs) Handles BtnFillDGVFromArray.Click
Dim Arr(5) As String
' This to give the array initial values to aviod the null reference
For i = 0 To 4
Arr(i) = Nothing
Next
' Add some strings to the array
For i = 0 To 4
Arr(i) = "ArrayVar(" & i & ")"
Next
DGV.Columns.Add("Col1", "Col1")
For i = 0 To UBound(Arr) - 1
DGV.Rows.Add(Arr(i).ToString)
Next
End Sub
End Class

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

Keep focus on row after datagridview update

I'm creating an VB windows application. The point of the application is a simple DataGridView where I'm fetching a View from a SQL Server database.
The DataGridView is refreshed every second so I could see new data income in my GridView.
The problem is keeping focus on row after the refresh. I need the solution, where after I click a row, or a cell it keeps me on it even after the refresh.
Here is my code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Refresh every 1 sec
Dim timer As New Timer()
timer.Interval = 1000
AddHandler timer.Tick, AddressOf timer_Tick
timer.Start()
'TODO: This line of code loads data into the 'XYZDataSet.view1' table. You can move, or remove it, as needed.
Me.View1TableAdapter.Fill(Me.XYZDataSet.view1)
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
For i As Integer = 0 To Me.DataGridView1.Rows.Count - 1
If Me.DataGridView1.Rows(i).Cells("DayTillDelivery").Value <= 30 Then
Me.DataGridView1.Rows(i).Cells("DayTillDelivery").Style.ForeColor = Color.Red
End If
Next
End Sub
Private Sub timer_Tick(ByVal sender As Object, ByVal e As EventArgs)
'Calling refresh after 1 second and updating the data
Me.DataGridView1.Refresh()
Me.View1TableAdapter.Fill(Me.XYZDataSet.view1)
End Sub
End Class
I've solved a similar problem in the past by storing the indexes of the selected cell in a variable before doing the refresh, so I'm able to restore the selection by calling DataGridView.Rows(selRow).Cells(selCol).Selected = True after the update.
Edit - Sample Code:
To later readers:Please take a look at Edit#2 where I describe a better method to re-select the previous selected cell!
Sample Code:
' Variables for remembering the indexes of the selected cell
Dim selRow As Integer
Dim selCol As Integer
' Check if there is a selected cell to prevent NullPointerException
If DataGridView1.SelectedCells().Count > 0 Then
selRow = DataGridView1.CurrentCell.RowIndex
selCol = DataGridView1.CurrentCell.ColumnIndex
End If
' Dummy "update"
' don't forget to clear any existing rows before adding the new bunch (only if you always reloading all rows)!
DataGridView1.Rows.Clear()
For index = 1 To 20
DataGridView1.Rows.Add()
Next
' Check if there are "enough" rows after the update,
' to prevent setting the selection to an rowindex greater than the Rows.Count - 1 which would
' cause an IndexOutOfBoundsException
If (DataGridView1.Rows.Count - 1) > selRow Then
' Clear selection and then reselect the cell that was selected before by index
DataGridView1.ClearSelection()
' For the next line of code, there is a better solution in Edit #2!
DataGridView1.Rows(selRow).Cells(selCol).Selected = True
End If
Please note:
This procedure requires you to add the rows in the exact same order that you have added them before the update, as only the .Index of the selected row is stored in the variable. If you readding the rows in a different order, then not the same row but the row at the same position will be selected after the refresh.
You should add check if there is a selected row at all (to prevent a NullPointerException) and if there are "enough" rows in the DataGridView after the refresh, to prevent an IndexOutOfBoundsException.
This only works if the DataGridView1.SelectionMode is to something that actually selects rows, like FullRowSelect.
Don't forget to clear any existing rows before adding new ones by updating (only if you always reloading all rows).
Edit 2 - RowHeader triangle and accidental MultiSelect
As stated in the comments below, there was an odd behavior that would lead to an accidental MultiSelect, if the user holds down the mouse button past the refresh cycle. Also, the RowHeader triangle was not set to the correct row.
After some research I found a solution to this behavior. Instead of setting the .Selected-property of a given cell to True, set the .CurrentCell-property of the DataGridView to the cell you would like to select!
In code, this means changing
DataGridView1.Rows(selRow).Cells(selCol).Selected = True
to
DataGridView1.CurrentCell = DataGridView1.Rows(selRow).Cells(selCol)
and there you go. :-)
Before Fill, store the CurrentRow values and currenCell column:
Dim currentColumnIndex As Integer = 0 ;
Dim currentValues As List(Of Object) = If(DataGridView1.CurrentRow Is Nothing, Nothing, New List(Of Object)())
If currentValues IsNot Nothing Then
For i As Integer = 0 To DataGridView1.Columns.Count - 1
currentValues.Add(DataGridView1.CurrentRow.Cells(i).Value)
Next
currentColumnIndex = DataGridView1.CurrentCell.ColumnIndex;
End If
After Fill, search the row corresponding to stored values:
Dim i As Integer = 0
While i < DataGridView1.Rows.Count AndAlso currentValues IsNot Nothing
Dim areIdentical As Boolean = True
Dim j As Integer = 0
While j < DataGridView1.Columns.Count AndAlso areIdentical
areIdentical = DataGridView1.Rows(i).Cells(j).Value = currentValues(j)
j += 1
End While
If areIdentical Then
DataGridView1.CurrentCell = DataGridView1.Rows(i).Cells(currentColumnIndex)
currentValues = Nothing
End If
i += 1
End While
Note: the "For/While" loop coding is perhaps not optimal because it results from automatic conversion from C# to vb.net.
C# fix code , next reload pattern
if (dataGridView7.SelectedCells.Count > 0)
{
//MessageBox.Show(selcell + "------"+dataGridView7.CurrentCell.ColumnIndex.ToString());
if (selcell > 0 && dataGridView7.CurrentCell.ColumnIndex==0) { }else
{
selrow = dataGridView7.CurrentCell.RowIndex;
selcell = dataGridView7.CurrentCell.ColumnIndex;
}
}
loaddataJobsall();
dataGridView7.ClearSelection();
dataGridView7.Rows[selrow].Cells[selcell].Selected = true;

Why is gridview.selectedColumns nothing?

I want to run a code like this, but it always jumps over the loop, so I see no line in the console.
That means that selectedColumns is empty. My assumption was that I (or the user) select a cell from a Column and then, selectedColummns are +1. But as it looks, it doesnt work. Then I tried to set proberties of selectionMode to select full columns, but then an exception is thrown:
"System.InvalidOperationException" Additional Information: the SortMode cannot be Automatic, if full Column selection is selected.
I don't know what SortMode is.
For Each col As DataGridViewColumn In datagridview2.SelectedColumns
Console.Write(datagridview2.SelectedColumns.Count)
Console.Write("1")
Next
Any Ideas how to get that the columns into selectedColumns?
Here my code that solved my problem, but I guess it is not the smartest one:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim body As String = ""
Dim myWriter As New StreamWriter("H:\downloads\test.csv", True)
Dim list As List(Of Integer) = New List(Of Integer)
For Each cell As DataGridViewCell In datagridview2.SelectedCells
If list.Contains(cell.ColumnIndex) = False Then
list.Add(cell.ColumnIndex)
End If
Next
For i = 0 To datagridview2.Rows.Count - 1
For ix = 0 To datagridview2.Columns.Count - 1
If list.Contains(ix) Then
If datagridview2.Rows(i).Cells(ix).Value IsNot Nothing Then
body = body + datagridview2.Rows(i).Cells(ix).Value.ToString + ";"
Else
body = body + ";"
End If
End If
Next
myWriter.WriteLine(body)
body = ""
Next
myWriter.Close()
End Sub
You need to do this after the selected changed event has fired.
For example:
Private Sub Mydg_ColSelected(sender As Object, e As SelectionChangedEventArgs) Handles datagridview2.SelectionChanged
For Each col As DataGridViewColumn In datagridview2.SelectedColumns
Console.Write(datagridview2.SelectedColumns.Count)
Console.Write("1")
Next
End Sub
Or if this isn't what you are after, then try handling the ColumnHeaderMouseClick event instead. I'm not sure what technology you are using, e.g Winforms, WPF, silverlight

Capturing value of DataGridView CheckBox in VB.Net

I have a datagridview (unbound). Fields are Name, Family Name and Phone No and a checkbox colum.
There are ten rows in that DataGridView.
There is an OK button
I need to get message of showing which rows user has checked. The message should appear when user clicks on the OK button. There could be several messages, checking each row one by one, in a loop.
I am not able to get this message. I tried following code in OK button :
Dim strCB As String = dgvChooseQs.Rows(0).Cells(3).Value.ToString
Cell(3) is my checkbox. Do not consider Rows(0), at the moment I am just checking value at row 0
Thanks for your help.
Furqan
Do not use the cell index. Your checkbox column must have a name so you should use it.
Otherwise, what you want to do would be something like this
For each oRow as DataGridViewRow in dgvChooseQs.Rows
If oRow.Cells("ColNamE").Value = True then
'do whatever you need to do.
End if
Next
If you feel you need to cast the column, then you can use CType, but the type is DataGridViewCheckBoxCell, not CheckBox.
You need to do something like this:
if ctype(dgvChooseQs.Rows(0).findcontrol("whateverYourCheckBoxIsNamed"), checkbox).checked then
'throw the message
end if
You may cast the cell value to Boolean, and then check it, as follows:
Dim RowIndex As Integer = ...
Dim ColumnIndex As Integer = ...
Dim IsTicked As Boolean = CBool(DataGridView1.Rows(RowIndex).Cells(ColumnIndex).Value)
If IsTicked Then
MessageBox.Show("You ticked the box.")
Else
MessageBox.Show("You cleared the box.")
End If
Only the third example worked for me but I had to add a Timer
Private Sub DgvElencoFile_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles DgvElencoFile.CellClick
'Variabili gestione programma
Dim numerocolonnaSelezionata As Integer
Dim numeroColonnaSelezionataPerDowonload As Integer
Dim numeroRigaSelezionata As Integer
numeroRigaSelezionata = e.RowIndex
NumerocolonnaSelezionata = e.ColumnIndex
If NumeroRigaSelezionata < 0 Then
ClaFunzSgnSon.SegnaleSonoro(ClaFunzSgnSon.EnTipoSgnSon.ErroreImpostazioneDati)
GoTo FineSubFunz
End If
numeroColonnaSelezionataPerDowonload = -1
If DgvElencoFile.Rows(numeroRigaSelezionata).Cells(ClnDownLoad.Name).Selected Then numeroColonnaSelezionataPerDowonload = numerocolonnaSelezionata
If numeroColonnaSelezionataPerDowonload >= 0 Then
TimVisCheckDownLoad.Start()
End If
FineSubFunz:
End Sub
Private Sub TimVisCheckDownLoad_Tick(sender As Object, e As EventArgs) Handles TimVisCheckDownLoad.Tick
TimVisCheckDownLoad.Stop()
Dim isTickedOn = CBool(DirectCast(DgvElencoFile.CurrentCell, DataGridViewCheckBoxCell).EditingCellFormattedValue)
If isTickedOn Then
MessageBox.Show("You ticked the box.")
Else
MessageBox.Show("You cleared the box.")
End If
End Sub
I found a simple solution.
Just change the cell focus after click on cell.
Private Sub DGV_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DGV.CellContentClick
If e.ColumnIndex = "Here checkbox column id or name" Then
DGV.Item(e.ColumnIndex, e.RowIndex + 1).Selected = True
'Here your code
MsgBox DGV.Item(e.ColumnIndex, e.RowIndex).Value
End If
End Sub
Don't forget to check if the column of your (ckeckbox + 1) index exist.
Set type of grid in dataGridView to 'DataGridViewCheckBoxXColumn' instead of DataGridViewCheckBoxColumn.
all problems will be solved
The post is old but it can help in need:
You have these three properties after casting your cell:
Private Sub YourDataGridView_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles YourDataGridView.CellMouseClick
Dim b, b1, b2 As Boolean
b = DirectCast(YourDataGridView.CurrentCell, DataGridViewCheckBoxCell).EditingCellValueChanged
b1 = CBool(DirectCast(YourDataGridView.CurrentCell, DataGridViewCheckBoxCell).EditingCellFormattedValue)
b2 = CBool(DirectCast(YourDataGridView.CurrentCell, DataGridViewCheckBoxCell).EditedFormattedValue)
End Sub
it's a long time since this question was sent, but can be useful this answer to anybody with the same issue. In my case, I used (I'm using your notation):
dgvChooseQs.Item(6, vCont).State
where 6 is the checkbox column number, in my case column 6. vCont is an iteration counter in a FOR NEXT loop. If State equals 32, checkbox was checked, else State will be zero. I hope this can be of help.