DataGridView loses cell formatting from DataTable.AcceptChanges - vb.net

VB2010. I have researched this issue and cannot seem to find a reason for it or a workaround. What I have is a DataGridView that is bound to a DataTable. I allow the user to select Edit mode which turns ON/OFF the ReadOnly property. Once ReadMode=True I make sure to set the DataTable to AcceptChanges. When this property is set all my cell formatting disappears.
I do this on form load:
Private Sub frmMain_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
dgv.DataSource = Nothing
dgv.DataSource = GetTripData()
dgv.AutoResizeColumns()
dgv.ClearSelection()
dgv.ReadOnly = True
End Sub
Then the user can click on a menu item to go into Edit Mode:
Private Sub mnuEditMode_Click(sender As System.Object, e As System.EventArgs) Handles mnuEditMode.Click
If mnuEditMode.Checked Then
dgv.ReadOnly = False
dgv.AllowUserToAddRows = True
dgv.AllowUserToDeleteRows = True
Else
dgv.ReadOnly = True
dgv.AllowUserToAddRows = False
dgv.AllowUserToDeleteRows = False
'accept all changes. if we dont do this any row that is deleted will still exist in the DataTable.
Dim dt As DataTable = CType(dgv.DataSource, DataTable)
If dt IsNot Nothing Then
dt.AcceptChanges() 'note: this causes custom cell font to be cleared
End If
End If
End Sub
Once in edit mode they can dictate which cells to change. Two cells they put in the list to change are treated a such:
'update the proper cells via the DataGridView
dgv.Rows(2).Cells(5).Value = "HOME"
dgv.Rows(2).Cells(6).Value = 10
'bold the cell's font in the DataGridView
Dim styleUpdated As New DataGridViewCellStyle
styleUpdated.Font = New Font(dgv.Font, FontStyle.Bold)
dgv.Rows(2).Cells(6).Style = styleUpdated
dgv.Rows(2).Cells(6).Style = styleUpdated
'refresh the DGV
dgv.Refresh()
This works! I can see the changes in the DGV. Now they are done with editing the data so they click on the menu item to set Edit Mode Off and that sets dgv.ReadOnly=True and I also set dt.AcceptChanges. This last method AcceptChanges clears all the bold fonts on modified cells.
Is this expected behavior? If so what suggestions are there to keep my edited cell formatting?

This isn't really an answer but I want to post a significant piece of code so I'm posting it as an answer. I just tested the following code and it worked for me, in that the bold text remained as the two Buttons were clicked.
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim table As New DataTable
With table.Columns
.Add("Id", GetType(Integer))
.Add("Name", GetType(String))
.Add("Age", GetType(Integer))
End With
With table.Rows
.Add(1, "Mary", 20)
.Add(2, "Paul", 30)
.Add(3, "Peter", 40)
End With
DataGridView1.DataSource = table
Dim style = DataGridView1.Rows(1).Cells(1).Style
style.Font = New Font(DataGridView1.Font, FontStyle.Bold)
DataGridView1.Rows(1).Cells(1).Style = style
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
With DataGridView1
.ReadOnly = True
.AllowUserToAddRows = False
.AllowUserToDeleteRows = False
End With
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
With DataGridView1
.ReadOnly = False
.AllowUserToAddRows = True
.AllowUserToDeleteRows = True
End With
End Sub
End Class
I'd suggest that you give that code a go and, if it works for you, you know that there's something else going on in your original project. You can then modify that test project slowly to make it more and more like your existing project and you should then be able to see where this functionality breaks.

I looked some more and I think the cell formatting clearing is expected behavior. So I came up with a small routine that will save each cell's formatting and then re-apply it after the AcceptChanges. Note that my DataTable is small so you may get a performance hit if you have a large dataset. Please provide any feedback if I have missed something:
'updated routine to implement AcceptChanges
'dt.AcceptChanges() 'note: this causes custom cell font to be cleared
DgvAcceptChanges(dgvMain)
''' <summary>
''' this routine will take a DataGridView and save the style for each cell, then it will take it's DataTable source and accept any
''' changes, then it will re-apply the style font to each DataGridView cell. this is required since DataTable.AcceptChanges will
''' clear any DataGridView cell formatting.
''' </summary>
''' <param name="dgv">DataGridView object</param>
''' <remarks>Could be extended to do other things like cell ReadOnly status or cell BackColor.</remarks>
Public Sub DgvAcceptChanges(dgv As DataGridView)
Dim dt As DataTable = CType(dgv.DataSource, DataTable)
If dt IsNot Nothing Then
'save the DataGridView's cell style font to an array
Dim cellStyle(dgv.Rows.Count - 1, dgv.Columns.Count - 1) As DataGridViewCellStyle
For r As Integer = 0 To dgv.Rows.Count - 1
'the DataGridViewRow.IsNewRow Property = Gets a value indicating whether the row is the row for new records.
'Remarks: Because the row for new records is in the Rows collection, use the IsNewRow property to determine whether a row
'is the row for new records or is a populated row. A row stops being the new row when data entry into the row begins.
If Not dgv.Rows(r).IsNewRow Then
For c As Integer = 0 To dgv.Columns.Count - 1
cellStyle(r, c) = dgv.Rows(r).Cells(c).Style
Next c
End If
Next r
'this causes custom cell font to be cleared in the DataGridView
dt.AcceptChanges()
're-apply the DataGridView's cell style font from an array
For r As Integer = 0 To dgv.Rows.Count - 1
If Not dgv.Rows(r).IsNewRow Then
For c As Integer = 0 To dgv.Columns.Count - 1
dgv.Rows(r).Cells(c).Style.Font = cellStyle(r, c).Font
Next c
End If
Next r
End If
End Sub

Related

DataGridView + TextBox How to colorate more and different values

I have a problem, with DataGridView's CellFormatting. The cells are colored by the search result from a TextBox. When I search for 2 numbers together, they are no longer colored. What should I do?
I state that I am using CONCAT_WS to load the table in DataGridView. What can I do?
Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting
Try
If e.ColumnIndex = 3 And e.Value IsNot Nothing Or e.ColumnIndex = 4 And e.Value IsNot Nothing Or e.ColumnIndex = 5 And e.Value IsNot Nothing Or e.ColumnIndex = 6 And e.Value IsNot Nothing Or e.ColumnIndex = 7 And e.Value IsNot Nothing Then
If String.IsNullOrEmpty(txtRefreshFiltra.Text) Then
txtRefreshFiltra.Text = ""
End If
Dim sum6 As String = Convert.ToInt32(e.Value)
If sum6 = txtRefreshFiltra.Text Then
e.CellStyle.BackColor = Color.Gold
e.CellStyle.ForeColor = Color.Black
End If
End If
Catch ex As Exception
MsgBox(ex.Message) 'show error msg'
End Try
End Sub
My connection
Public Sub FilterData(ValueToSearch As String)
Try
Dim SearchQyery As String = "SELECT * FROM LottoDeaBendata WHERE CONCAT_WS([Estratto1],[Estratto2],[Estratto3],[Estratto4],[Estratto5])LIKE'%" & ValueToSearch & "%'"
Dim command As New SqlCommand(SearchQyery, connection)
connection.Open()
Dim table As New DataTable()
Dim adapter As New SqlDataAdapter(command)
adapter.Fill(table)
DataGridView1.DataSource = table
connection.Close()
Catch ex As Exception
MsgBox(ex.Message) 'show error msg'
End Try
End Sub
Upload by button
Private Sub btnFiltraDati_Click(sender As Object, e As EventArgs) Handles btnFiltraDati.Click
FilterData(txtRefreshFiltra.Text)
End Sub
There are a few things you may want to consider to color the cells as you describe. First, using the grids CellFormatting event may not necessarily be the best choice. This event will fire once for each cell when the data is loaded into the grid and this is fine and colors the cells as we want when the data is loaded, however, it also may fire if the user simply moves the cursor over a cell or the user scrolls the grid.
In both the cases of the user moving the cursor over a cell or scrolling the grid, clearly demonstrates that the cells will get re-colored unnecessarily. In other words, if the text in the text box has not changed or a cells value has not changed, then, re-coloring the cell(s) is superfluous.
Given this, the only drawback to NOT using the grids CellFormatting event is that our code will have to color the cells AFTER the grid is loaded with data. This means we will need a method to loop through all the rows of the grid to check and color the cells. This method to color all the cells is also going to be needed if the text in the text box changes. So, making this method makes sense so we can call it when the data is loaded and also when the text box text changes.
So given all this, to simplify things, I suggest you create a method that takes a single DataGridViewCell. The method will get the comma separated values from the text box and compare the cells value to the values in the text box and if one matches, then we simply color the cell, otherwise do not color the cell.
This method is below. First, we check if the cell is not null and actually has some value. Then, we take the string in the text box and split it on commas. Then we start a loop through all the values in the split string from the text box and if a match is found, then we simply color the cell and exit the for each loop.
Private Sub ColorCell(cell As DataGridViewCell)
If (cell.Value IsNot Nothing) Then
Dim target = cell.Value.ToString()
If (Not String.IsNullOrEmpty(target)) Then
cell.Style.BackColor = Color.White
cell.Style.ForeColor = Color.Black
Dim split = txtRefreshFiltra.Text.Trim().Split(",")
For Each s As String In split
If (target = s.Trim()) Then
cell.Style.BackColor = Color.Gold
cell.Style.ForeColor = Color.Black
Exit For
End If
Next
End If
End If
End Sub
The method above should simplify looping through all the rows in the grid to color the proper cells. This method may look something like below and we would call this method once after the data is loaded into the grid and also when the text in the text box changes.
Private Sub ColorAllCells()
For Each row As DataGridViewRow In DataGridView1.Rows
ColorCell(row.Cells(3))
ColorCell(row.Cells(4))
ColorCell(row.Cells(5))
ColorCell(row.Cells(6))
ColorCell(row.Cells(7))
Next
End Sub
Lastly, the two event methods that we need to capture when the user changes a cells value in the grid in addition to when the user changes the text in the text box.
Private Sub txtRefreshFiltra_TextChanged(sender As Object, e As EventArgs) Handles txtRefreshFiltra.TextChanged
ColorAllCells()
End Sub
Private Sub DataGridView1_CellValueChanged(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged
If (e.RowIndex >= 0) Then
If (e.ColumnIndex = 3 Or e.ColumnIndex = 4 Or e.ColumnIndex = 5 Or e.ColumnIndex = 6 Or e.ColumnIndex = 7) Then
ColorCell(DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex))
End If
End If
End Sub
Edit per OP comment…
There are definitely a couple of things we can do to speed up the current code above, like take out the call to ColorAllCells in the text boxes TextChanged event.
The TextChanged event will fire when the user types a single character. Example, if the user wants to color the cells that are “55”, then, when the user types the first “5” into the text box… then the TextChanged event will fire and the code will color all the cells with “5”. Then when the user types the second “5”, the cells will be un-colored/colored again.
So, one way we can prevent the unnecessary coloring as described above is to NOT call the ColorAllCells method in the text boxes TextChanged event and simply put the ColorAllCells method into a button click. In other words, the user types what they want into the text box… THEN clicks a button to color the cells.
In addition, if you look at the ColorCell method, you may note that each time the method is called, the code is splitting the same string over and over with … Dim split = txtRefreshFiltra.Text.Trim().Split(",") … this is potentially redundant in a sense that the text … txtRefreshFiltra.Text may not have changed.
Therefore, to remedy this and only split the txtRefreshFiltra.Text when needed, we will use a global variable called something like currentSplit that holds the current split of the text box. Then we would “update” the currentSplit variable only when needed… like in its TextChanged event.
This should somewhat speed things up. In my small tests, it took approximately 10 seconds to color the cells the FIRST time. Subsequent coloring of the cells when the text box value was changed took less than 1 second.
First make a global variable to hold the current text boxes split values…
Dim currentSplit As String()
Then change the other methods as shown below…
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim dt = GetDT()
DataGridView1.DataSource = dt
currentSplit = txtRefreshFiltra.Text.Trim().Split(",")
End Sub
Private Sub ColorCell(cell As DataGridViewCell)
If (cell.Value IsNot Nothing) Then
Dim target = cell.Value.ToString()
If (Not String.IsNullOrEmpty(target)) Then
cell.Style.BackColor = Color.White
cell.Style.ForeColor = Color.Black
For Each s As String In currentSplit
If (target = s.Trim()) Then
cell.Style.BackColor = Color.Gold
cell.Style.ForeColor = Color.Black
Exit For
End If
Next
End If
End If
End Sub
Private Sub txtRefreshFiltra_TextChanged(sender As Object, e As EventArgs) Handles txtRefreshFiltra.TextChanged
currentSplit = txtRefreshFiltra.Text.Trim().Split(",")
End Sub
And finally, a button click event to color the cells. I added a stop watch to time how long it takes to color the cells.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sw As Stopwatch = New Stopwatch()
Debug.WriteLine("Starting coloring of cells -------")
sw.Start()
ColorAllCells()
sw.Stop()
Debug.WriteLine("It took: " + sw.Elapsed.TotalSeconds.ToString() + " to color the cells of 100,000 rows with 10 columns")
End Sub

Add data into new added row in `DataGridView` from `DataBindingSource`

In Form4 i have a DataGridView named DbTableDataGridView.
In Form3 there is a set of fields (text boxes) that are all bound to the DbTableBindingSource . When I run application the Form4 shows up. There is a button to open new form (Form3) and in there enter details about customers to be added as new row into database (DataGridView). My code for the "Add" button in Form4 looks like this:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.DbTableDataGridView.Refresh()
Me.DbTableBindingSource.AddNew()
Form3.ShowDialog()
Form3.ImiéTextBox.Text = ""
Form3.NazwiskoTextBox.Text = ""
Form3.Numer_TelefonuTextBox.Text = ""
Form3.Numer_RejestracyjnyTextBox.Text = ""
Form3.MarkaTextBox.Text = ""
Form3.ModelTextBox.Text = ""
Form3.Poj_SilnikaTextBox.Text = ""
Form3.RocznikTextBox.Text = ""
Form3.PaliwoTextBox.Text = ""
Form3.Data_PrzyjeciaDateTimePicker.Value = DateTime.Now
Form3.RichTextBox1.Text = ""
End Sub
It does add new row, selects it and clears entries in the text boxes (that are bound into 'DbTableBindingSource'.
In this form after I fill in all the fields I press button save:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Me.Validate()
Form4.DbTableBindingSource.EndEdit()
Me.DbTableTableAdapter.Update(CartronicDBDataSet.dbTable)
TableAdapterManager.UpdateAll(CartronicDBDataSet)
DbTableTableAdapter.Fill(Form4.CartronicDBDataSet.dbTable)
MsgBox("Saved")
Catch ex As Exception
MessageBox.Show("Blad zapisu. Sprobuj ponownie. W razie potrzeby zamknij, a nastepnie uruchom ponownie program Cartronic")
End Try
End Sub
It goes to the message "Saved" but actually does not fill in added new recently.
Any thoughts?
There is no link that I can see between Form3 and your data.
I'd recommend passing the newly created data row to a new instance of Form3.
Get the reference to your newly added row
Create a new Form3 (avoid default instance forms, they're ugly and evil). This will mean you don't need to clear the textboxes as you have a brand new form every time.
Pass the datarow into your form where you will bind it directly to the textboxes
Dim newRow = CType(Me.DbTableBindingSource.AddNew(), DataRow)
Using frmEditor As New Form3
frmEditor.DataSource = newRow
frmEditor.ShowDialog()
End Using
In form3 add the property (or preferably a constructor)
Private mDataSource As DataRow
Public Property DataSource As DataRow
Get
Return mDataSource
End Get
Set(value As DataRow)
mDataSource = value
Me.ImiéTextBox.DataBindings.Add("Text", mDataSource, "ImiéFieldName")
' ....
End Set
End Property
If you use this approach then you can get rid of all of the textbox clearing code.
I have done what you have suggested but little bit simpler.
Assigned all text boxes to each cell in current row as follows:
Form4.DbTableDataGridView.CurrentRow.Cells(5).Value = Me.NazwiskoTextBox.Text.ToString
Form4.DbTableDataGridView.CurrentRow.Cells(4).Value = Me.ImiéTextBox.Text.ToString
It works fine.
Cheers

DataGridView is not showing first row after removing other rows

I am having a problem that I have been debugging for some days.
Some context, I have an application where I store the data (in the following code a list of class Expediente) in xml files using serialization. For displaying the data I deserialize it and then I create a datatable which I use as the datasource for the datagrid. I added a datagridcheckbox column to check the ones to delete.
In the datagrid I have a toolstrip button that when clicked it removes the checked -or checked in edit mode thus the line CType(dgvr.Cells(0).GetEditedFormattedValue(dgvr.Index, DataGridViewDataErrorContexts.Commit), Boolean) = True- elements from the datasource and persists the datasource to an xml.
The problem is that when deserializing the xml and loading it again to a datatable and binding the datagrid datasource to it, it removes the first row. If I close the application and open it, the first row appears.
I have debuged and in the datatable the correct numbers of rows appear. Moreover, I have narrowed the problem to the binding navigator, when it sets its binding source to the datable there the first row of the datagrid disappears.
I paste a simplified version of the code, I can provide more if needed.
Note that if in LoadGridExpedientes() I comment the lines
navExpedientes.BindingSource = Nothing
navExpedientes.BindingSource = bs
The first row doesn't disappear but obviously the counter of the binding navigator does not update.
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim chk As New DataGridViewCheckBoxColumn()
grdExpedientes.Columns.Add(chk)
chk.HeaderText = ""
chk.Name = "chk"
'fills a datatable from an xml, it works ok, it fills it with the correct amount of rows
Dim dt As DataTable = Sistema.getInstance.getDataExpedienteForGrid()
Dim bs As New BindingSource
bs.DataSource = dt
grdExpedientes.DataSource = bs
navExpedientes.BindingSource = bs
For i As Integer = 0 To grdExpedientes.Rows.Count - 2
grdExpedientes.Rows(i).Cells(0).Value = True
Next
End Sub
Private Sub LoadGridExpedientes()
grdExpedientes.DataSource = Nothing
navExpedientes.BindingSource = Nothing
grdExpedientes.Columns.Clear()
grdExpedientes.Rows.Clear()
'This is to know if there is already the checkbox column
If Not (grdExpedientes.Columns.Count > 0 AndAlso grdExpedientes.Columns(0).Name = "chk") Then
Dim chk As New DataGridViewCheckBoxColumn()
grdExpedientes.Columns.Add(chk)
chk.HeaderText = ""
chk.Name = "chk"
End If
Dim dt As DataTable = Sistema.getInstance.getDataExpedienteForGrid()
Dim bs As New BindingSource
bs.DataSource = dt
grdExpedientes.DataSource = bs
navExpedientes.BindingSource = bs
End Sub
Private Sub navExpedientesDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles navExpedientesDelete.Click
For i As Integer = 0 To grdExpedientes.Rows.Count - 2
Dim dgvr As DataGridViewRow = grdExpedientes.Rows(i)
If CType(dgvr.Cells(0).Value, Boolean) = True Or _
CType(dgvr.Cells(0).GetEditedFormattedValue(dgvr.Index, DataGridViewDataErrorContexts.Commit), Boolean) = True Then
Dim draux As DataGridViewRow = dgvr
Dim expABorrar As Expediente = CType((From elem As Expediente In Sistema.listExpedientes
Where elem.Expediente = CType(draux.Cells("Expediente (Ficha)").Value, String)
Select elem).FirstOrDefault, Expediente)
Sistema.listExpedientes.Remove(expABorrar)
End If
Next
If System.IO.File.Exists(Sistema.pathListExpedientes) Then
System.IO.File.Delete(Sistema.pathListExpedientes)
End If
Dim sw As System.IO.TextWriter = New System.IO.StreamWriter(Sistema.rutaListaExpedientes, 0)
Serializer(Of Expediente).Serialize(Sistema.listExpedientes, sw, New List(Of Type) From {GetType(Movimiento)})
sw.Close()
LoadGridExpedientes()
End Sub
The problem was that I was using the delete toolstrip button that comes with the binding navigator, it seems that when clicked it has 'embedded' that it deletes the row that was selected that by default is the first one.
I created a new toolstrip button in the binding navigator and the problem was solved. I do not know why not updating the binding navigator binding source also avoided the first row from being removed.

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;

When the last row in a DataGridView is selected, a value from the previous row is returned instead of from the selected row

I have a DataGridView on a form which is populated by a dataset. Everything works except one thing. In the first column I have id numbers. The user clicks on some row, and the id number from the column is taken to be deleted from the db. Every id is taking correctly except the last row - it is a new row, as you know, because the user can create new records in the database. Anyhow, if the user makes a mistake and selects this row, my code shown below somehow gets the id number from the previous row. I don't know how to avoid that issue. I am taking it using this code:
dgv.CurrentRow.Cells(0).Value
Edit:
i've added code i am using to better understand the situation:
Form Load event:
Private Sub FrmNewRodzaj_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim del As DelegateGridRefresh = New DelegateGridRefresh(AddressOf FillGrid)
Dim del2 As DelegateGridRefresh = New DelegateGridRefresh(AddressOf AlignGrid)
del = [Delegate].Combine(del, del2)
AddHandler EventGridRefresh, AddressOf del.Invoke
del.Invoke()
End Sub
Fill Grid method:
Private Sub FillGrid()
NewRodzaj = New MachineRodzaj()
dgv.DataSource = NewRodzaj.GetRodzaje.Tables(0)
End Sub
GetRodzaje method:
Public Function GetRodzaje() As DataSet
Dim con As New SqlConnection(strcon)
Dim cmd As New SqlCommand("Select * from tbMachRodzajList", con)
con.Open()
GetRodzajeDataAdapter = New SqlDataAdapter(cmd)
GetRodzajeDataAdapter.Fill(GetRodzajeDataSet, "trial1")
Return GetRodzajeDataSet
End Function
AlignGrid method:
Private Sub AlignGrid()
dgv.RowsDefaultCellStyle.BackColor = Color.SkyBlue 'LightSkyBlue
dgv.AlternatingRowsDefaultCellStyle.BackColor = Color.LightBlue
dgv.ColumnHeadersBorderStyle = DataGridViewCellBorderStyle.None
dgv.AllowUserToAddRows = True
dgv.DefaultCellStyle.Font = New Font("Tahoma", 9)
Me.dgv.DefaultCellStyle.SelectionForeColor = Color.Red
Me.dgv.DefaultCellStyle.SelectionBackColor = Color.Yellow
Me.dgv.RowHeadersVisible = False
Dim column0 As DataGridViewColumn = dgv.Columns(0)
column0.Visible = False
Dim ColNazwa As DataGridViewColumn = dgv.Columns(1)
ColNazwa.HeaderText = "Nazwa"
ColNazwa.[ReadOnly] = False
Dim ColOpis As DataGridViewColumn = dgv.Columns(2)
ColOpis.HeaderText = "Opis"
ColOpis.[ReadOnly] = False
Dim column3 As DataGridViewColumn = dgv.Columns(3)
column3.Visible = False
dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
Dim dgvColumnHeaderStyle As New DataGridViewCellStyle()
dgvColumnHeaderStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
dgv.ColumnHeadersDefaultCellStyle = dgvColumnHeaderStyle
'You cannot change the column and row header colours without disabling visual styles:
dgv.EnableHeadersVisualStyles = False
' Set the row and column header styles.
dgv.ColumnHeadersDefaultCellStyle.ForeColor = Color.WhiteSmoke
dgv.ColumnHeadersDefaultCellStyle.BackColor = Color.Firebrick
dgv.ColumnHeadersDefaultCellStyle.Font = New Font("Tahoma", 14)
End Sub
button method to save/update data:
Private Sub btnSave_Click(sender As System.Object, e As System.EventArgs) Handles btnZapisz.Click
NewRodzaj.MakeChanges()
RaiseEvent EventGridRefresh()
End Sub
MakeChanges method:
Public Sub MakeChanges()
MachineRodzajDAO.GetRodzajeMakeChanges()
End Sub
GetRodzajeMakeChanges method:
Public Sub GetRodzajeMakeChanges()
If Not GetRodzajeDataSet.HasChanges Then
MessageBox.Show("No changes no need to update", "Informacja", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
Dim cmdbuilder As New SqlCommandBuilder(GetRodzajeDataAdapter)
Dim i As Integer
Try
i = GetRodzajeDataAdapter.Update(GetRodzajeDataSet, "trial1")
MsgBox("Updated" & i & " records")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
End Sub
so the one is missing and i am fighting with is delete button after user select row to be deleted from db and click delete button, if he select newRow then message should appear - you selected wrong row. The id values are placed within column(0) when i use CurrentRow.Cells(0).Value if user click newRow then id is id of before row so i cannot just make check if value is nothing and also IsNewRow not working.
Private Sub btnDelete_Click(sender As System.Object, e As System.EventArgs) Handles btnUsun.Click
End Sub
Hope now will be clear enough
actually isNewRow works great
put it on Event dgv.CellClick for example
If dgv.CurrentRow.IsNewRow Then
'Cancel your code
Else
'Execute your code
End If
Edit: then check the row index like
dgv.NewRowIndex
that will always be the NewRowIndex
so if a user clicks a row or NewRow that row will become CurrentRow
you could then check stuff like
If dgv.CurrentRow.Index = dgv.NewRowIndex - 1 Then
'User clicked NewRow but CurrentRow is the one before the NewRow
End If
Edit: actually this is pretty straight forward
but you have to know what is happening on your DGV.
1.
user clicks NewRow and the ClickedCell just gets selected then u get the correct RowIndex with
dgv.SelectedCells(0).RowIndex
which is the same as
BenutzerDataGridView.NewRowIndex
and CurrentRow.Index will always be -1
User clicks NewRow and start typing. Now NewRow moves one Row down and the Row which is being edited becomes CurrentRow.
that's why i added the above to always ensure that it is not the NewRow
If dgv.CurrentRow.Index = dgv.NewRowIndex - 1 Then
this should actually be enough to do what you want ^^
last EDIT:
If dgv.SelectedCells(0).RowIndex = dgv.NewRowIndex Then
MsgBox("wrong row")
End If
or this way
If dgv.Rows(dgv.SelectedCells(0).RowIndex).IsNewRow Then
MsgBox("wrong row")
End If
i'm glad u got it sorted out ^^