refresh datagridview after cellformatting event - vb.net

I'm programming in Visual Basic Net and I fill a Datagridview with a MySql table manually. I want to change font, style of a row if meet some conditions.
The Datagridview.CellFormatting event can do that, but after leave the event my datagridview don't refresh. Below the code:
Private Sub gridUsers_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles gridUsers.CellFormatting
With DirectCast(sender, DataGridView)
If .CurrentRow.Cells("eliminado").Value Is "Si" Then
.CurrentRow.DefaultCellStyle.BackColor = Color.DarkRed
.CurrentRow.DefaultCellStyle.ForeColor = Color.White
ElseIf .CurrentRow.Cells("condicion").Value Is "No" Then
.CurrentRow.DefaultCellStyle.ForeColor = Color.DarkRed
.CurrentRow.DefaultCellStyle.Font = New Font("Verdana", 8, FontStyle.Strikeout Or FontStyle.Bold)
End If
End With
End Sub
I don't know why, but whenever I click any row in the grid, or scroll down and up, the lines' colors change. How to refresh the style of the cells in the datagridview
Thanks for your help...

Related

Set the text color of Combobox embedded in datagridview cell

I have a grid with few columns to it. I have mentioned a condition as if Cell value of column Amount < 0 then change the text colour of a that row to Gray. Now one of my column has "DataGridViewComboBox" embedded to it. Now when the <0 condition met, text of all other columns from that row turns gray except this "DataGridViewComboBox" Column.
I would like to know how can I set the Combobox's selected text's colour to Gray?
Private Function GetComboBoxColumn_Category() As DataGridViewComboBoxColumn
Dim ColCombo As New DataGridViewComboBoxColumn
Try
Using Connection = GetConnection()
da = New SqlDataAdapter("SELECT hKey 'iCategory', sCategory FROM tbl_CategoryList WHERE IsObsolete = 0", Connection)
dt = New DataTable
da.Fill(dt)
End Using
ColCombo.DataPropertyName = "iCategory"
ColCombo.HeaderText = "Category"
ColCombo.Name = "iCategory"
ColCombo.DataSource = dt
ColCombo.ValueMember = "iCategory"
ColCombo.DisplayMember = "sCategory"
ColCombo.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox
Catch ex As Exception
ImpensaAlert(ex.Message, MsgBoxStyle.Critical)
End Try
Return ColCombo
End Function '1
Private Sub PopulateExpenditureDetailGrid()
Dim TextBoxCell As DataGridViewTextBoxCell
Dim strSQL As String = ""
Dim dc_Category As DataGridViewComboBoxColumn
Dim dc_DelChk As New DataGridViewCheckBoxColumn
Try
DataGridExpDet.DataSource = Nothing
'DataGridExpDet.Columns.Clear()
Label15.Text = "Getting Detail Records..."
Application.DoEvents()
StrClosedYrs = BuildOpenOrClosedYrsStr(1) 'List Of Closed Years
dc_Category = GetComboBoxColumn_Category()
DataGridExpDet.Columns.Add(dc_Category)
Private Sub DataGridExpDet_CellLeave(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridExpDet.CellLeave
If DataGridExpDet.CurrentCell.ColumnIndex = DataGridExpDet.Columns("Amount").Index And Not String.IsNullOrEmpty(DataGridExpDet(DataGridExpDet.CurrentCell.ColumnIndex, DataGridExpDet.CurrentCell.RowIndex).EditedFormattedValue) Then
If DataGridExpDet(DataGridExpDet.CurrentCell.ColumnIndex, DataGridExpDet.CurrentCell.RowIndex).EditedFormattedValue < 0 Then
DataGridExpDet.Rows(DataGridExpDet.CurrentCell.RowIndex).DefaultCellStyle.ForeColor = Color.Gray
End If
End If
End Sub
Any help would be greatly appreciated.
Normally, to change the color of the text you change the .forecolor
ComboBox1.ForeColor = Color.Gray
will change the color of all the text located in a combobox.
However, I dont think that datagridview combo boxes have this option by default.
Whenever I do custom work like this, I usually use RadComboBox. They have tons of customization options that will allow you to accomplish whatever you need.
edit
Ah hah, found it! - Here you go
Apparently you do edit it just like a normal combobox.
You have two options. One is easy and the other is involved.
Give the column a Flat style. This will change the way the ComboBox looks. But if you're OK with that, then this is the easy approach. Simply add the following line to your DataGridViewComboBoxColumn creation:
ColCombo.FlatStyle = FlatStyle.Flat
Manually draw the ComboBox text in the correct color. To do so, in addition to your code, handle the DataGridView.CellPainting and DataGridView.EditingControlShowing events. This method is longer, but if you want to keep the look of the ComboBox then this option should work nicely.
' If the cell is a ComboBox cell: Grab the row ForeColor,
' Paint the cell as usual minus the text, then manually
' Paint the text in the correct color.
' This displays the cell text in the correct color when the cell is not in edit mode.
Private Sub DataGridExpDet_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles DataGridExpDet.CellPainting
If e.RowIndex >= 0 And e.ColumnIndex >= 0 Then
If TypeOf DataGridExpDet.Rows(e.RowIndex).Cells(e.ColumnIndex) Is DataGridViewComboBoxCell Then
Dim cell As DataGridViewComboBoxCell = DataGridExpDet.Rows(e.RowIndex).Cells(e.ColumnIndex)
Dim row As DataGridViewRow = DataGridExpDet.Rows(e.RowIndex)
Dim color As Color = If(row.DefaultCellStyle.ForeColor.Name = "0", color.Black, row.DefaultCellStyle.ForeColor)
Using brush = New SolidBrush(color)
Using format = New StringFormat()
e.Paint(e.ClipBounds, DataGridViewPaintParts.Background)
e.Paint(e.ClipBounds, DataGridViewPaintParts.Border)
e.Paint(e.ClipBounds, DataGridViewPaintParts.ContentBackground)
e.Paint(e.ClipBounds, DataGridViewPaintParts.ErrorIcon)
e.Paint(e.ClipBounds, DataGridViewPaintParts.Focus)
e.Paint(e.ClipBounds, DataGridViewPaintParts.SelectionBackground)
'Don't do the following one - that's what we're overriding.
'e.Paint(e.ClipBounds, DataGridViewPaintParts.ContentForeground)
format.LineAlignment = StringAlignment.Center
e.Graphics.DrawString(cell.FormattedValue, e.CellStyle.Font, brush, e.CellBounds, format)
e.Handled = True
End Using
End Using
End If
End If
End Sub
' Handle the ComboBox control's DrawItem event when showing.
' This draws the selected item and item options' texts in the correct color when in edit mode.
Private Sub DataGridExpDet_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles DataGridExpDet.EditingControlShowing
If TypeOf e.Control Is ComboBox Then
Dim cb As ComboBox = TryCast(e.Control, ComboBox)
cb.DrawMode = DrawMode.OwnerDrawFixed
RemoveHandler cb.DrawItem, AddressOf GridComboBox_DrawItem
AddHandler cb.DrawItem, AddressOf GridComboBox_DrawItem
End If
End Sub
' Draw the background and focus as normal, then manually
' draw the text values from the indexed datasource row of the
' corresponding DisplayValue column.
Private Sub GridComboBox_DrawItem(sender As Object, e As DrawItemEventArgs)
e.DrawBackground()
e.DrawFocusRectangle()
Dim cb As ComboBox = TryCast(sender, ComboBox)
Dim dt As DataTable = TryCast(cb.DataSource, DataTable)
Using brush = New SolidBrush(cb.ForeColor)
e.Graphics.DrawString(dt.Rows(e.Index).Item("sCategory"), e.Font, brush, e.Bounds)
End Using
End Sub

Why are there two lists when using autocomplete on combobox in datagridview?

I recently built a windows forms application using Visual Studio 2013 .Net 4.5 using VB.net. One of my users showed me this while using the app. In the datagridview, if they click the drop down button, then start typing, it overlays the autocomplete over the original dropdown. What am i doing wrong here?
Private Sub Data_CreateOrder_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles Data_CreateOrder.EditingControlShowing
If Data_CreateOrder.CurrentCell.ColumnIndex = 0 AndAlso TypeOf e.Control Is ComboBox Then
With DirectCast(e.Control, ComboBox)
.DropDownStyle = ComboBoxStyle.DropDown
.AutoCompleteMode = AutoCompleteMode.SuggestAppend
.AutoCompleteSource = AutoCompleteSource.ListItems
.SelectAll()
.BackColor = Color.White
End With
End If
End Sub
The behavior you are seeing should be expected. As a ComboBox, the full list of items will be visible (as seen in the background dropdown of your screenshot) because of:
.DropDownStyle = ComboBoxStyle.DropDown
The overlaying list of items is visible to suggest appending items and is simply a narrowed down list based on the current user input. This list is showing because of:
.AutoCompleteMode = AutoCompleteMode.SuggestAppend
If you want the user to see a narrowed list of options related to their input, this behavior should be expected. If you don't want this additional dropdown to appear, remove the above line of code.
I hope this can help you
Private Sub AdvancedDataGridView1_EditingControlShowing(sender As Object, e As DataGridViewEditingControlShowingEventArgs) Handles AdvancedDataGridView1.EditingControlShowing
Dim cbo As ComboBox
If TypeOf e.Control Is ComboBox Then`enter code here`
cbo = e.Control
cbo.DropDownStyle = ComboBoxStyle.DropDown
cbo.AutoCompleteMode = AutoCompleteMode.SuggestAppend
' cbo.AutoCompleteSource = AutoCompleteSource.CustomSource
cbo.AutoCompleteSource = AutoCompleteSource.ListItems
End If
End Sub
abdelaziz sebrou

datagridview editingcontrolshowing checkboxcell

I want to change the backcolor of the edited cell when I have a checkboxcolumn in my datagridview.
For textboxcolumns the backcolor is easy to set but for some reason I don't catch this event on the checkboxcolumn when it goes into edit mode.
Is there something different I need to do to handle this scenario? I am guessing comboboxcolumns are similarly different?
Based on thetimmer's suggested answer I added the following code to the cellbeginedit event of my datagridview but it has no effect on the coloring.
If e.ColumnIndex = datagridview1.Columns("checkboxcolumn").Index Then
Dim c As DataGridViewCheckBoxCell = datagridview1.CurrentCell
c.Style.BackColor = Color.Red
End If
This works once you've left the cell
Private Sub DataGridView1_CellBeginEdit(sender As System.Object, e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles DataGridView1.CellBeginEdit
Me.DataGridView1.CurrentCell.Style.BackColor = Color.Yellow
End Sub

DataGridview, disable Ctrl+Click

I have a datagridview as such:
With DataGridView1
.SelectionMode = DataGridViewSelectionMode.FullRowSelect
.ReadOnly = True
.AllowUserToAddRows = True
.MultiSelect = False
.EditMode = DataGridViewEditMode.EditProgrammatically
End With
When I do Ctrl + Click on last row my datagridview lost wanted functionality.
Sometimes select a row sometimes deselect and those little black triangle always jumps one row to lower.
I think this may be built in functionality for adding new data to grid.
Since I need my own Ctrl + Click on last row is there any chance to turn off those built in functionality so last row can behave as any other?
I am not sure about what you mean with a special functionality when Ctrl+Clicking on a cell. But if what you want is a code being triggered when a cell is clicked and Ctrl is pressed, you can rely on the CellMouseClick event:
Private Sub DataGridView1_CellMouseClick(sender As Object, e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseClick
If (Control.ModifierKeys = Keys.Control) Then
MessageBox.Show("CTRL & Click")
End If
End Sub

DataGridView only refreshing styles upon cell click

I have a DGV in VB.NET and VS2012. I am attempting to change the cell formatting of various cells dynamically. The following is my code:
Private Sub gridFinancial_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles gridFinancial.CellFormatting
Try
For Each row As chgltrDataSet.gridsourceRow In frmFinBatchChrg.ChgltrDataSet.gridsource.Rows
If gridFinancial.CurrentRow.Cells("CompBool").Value = True Then
Me.gridFinancial.CurrentRow.Cells(0).Style.BackColor = Color.Yellow
Me.gridFinancial.CurrentRow.Cells(1).Style.BackColor = Color.Yellow
Me.gridFinancial.CurrentRow.Cells(2).Style.BackColor = Color.Yellow
Me.gridFinancial.CurrentRow.Cells(3).Style.BackColor = Color.Yellow
Me.gridFinancial.CurrentRow.Cells(4).Style.BackColor = Color.Yellow
Me.gridFinancial.CurrentRow.Cells(5).Style.BackColor = Color.Yellow
Me.gridFinancial.CurrentRow.Cells(6).Style.BackColor = Color.Yellow
Me.gridFinancial.CurrentRow.Cells(7).Style.BackColor = Color.Yellow
Me.gridFinancial.CurrentRow.Cells(8).Style.BackColor = Color.Yellow
Me.gridFinancial.CurrentRow.Cells(0).ReadOnly = True
Me.gridFinancial.CurrentRow.Cells(1).ReadOnly = True
Me.gridFinancial.CurrentRow.Cells(2).ReadOnly = True
Me.gridFinancial.CurrentRow.Cells(3).ReadOnly = True
Me.gridFinancial.CurrentRow.Cells(4).ReadOnly = True
Me.gridFinancial.CurrentRow.Cells(5).ReadOnly = True
Me.gridFinancial.CurrentRow.Cells(6).ReadOnly = True
Me.gridFinancial.Update()
Me.gridFinancial.Refresh()
End if
Catch ex As Exception
End Try
End Sub
I have read this: http://msdn.microsoft.com/en-us/library/1yef90x0.aspx and maybe I'm missing something, but right now, with that code applied, my DataGridView will only reflect that code if I click one of the affected cells after the DataGridView has been painted. In other words, after the DataGridView has loaded, the cells will only be yellow after I click them (then all of the cells within that row that are supposed to be yellow, appear yellow). Why is this? I'm not sure what I'm doing wrong.
And as a side question, this cell formatting event fires at least 40-50 times before my DGV has even been drawn, and it's only a 6 row DataSource. Isn't there a better event trigger for this? I'm sure my code could be better, but that just seems highly inefficient.
The readonly properties in the above code work fine, so I know the event is triggering correctly.
Instead of setting the cell style like you are you can access the style through the DataGridViewCellFormattingEventArgs.
So something like this:
e.CellStyle.BackColor = Color.Yellow
Another thing to consider is that it is often better to attach your CellFormatting handler from within the DataBindingComplete event.
Private Sub DataGridView1_DataBindingComplete(sender As System.Object, e As System.Windows.Forms.DataGridViewBindingCompleteEventArgs) Handles DataGridView1.DataBindingComplete
AddHandler DataGridView1.CellFormatting, AddressOf Me.DataGridView1_CellFormatting
End Sub
This addresses some odd behaviour when the visual portion of the DataGridView is rendered by making sure that everything is done before your later events are attached.
This tip with the DataBindingComplete event should at least reduce the needless calls to CellFormatting - cell formatting fires every time a cell is updated. Once you are all up and running this is only once a user leaves a cell.