change color of DataGrid row - vb.net

I want to color entire rows of a System.Windows.Forms.DataGrid based on the content of one cell of the Row.
I couldn't find any way to do that, since there is no .Rows-Property of the DataGrid or a .Row-Property of the DataGridTextBoxColumn (or any similar).
Searching for solutions in the internet also didn't help me so far.
Switching to DataGridView is unfortunately not an option.
So the question remains: How can I change the color of a DataGrid row?

Thanks to this link (provided by #Monty) I was able to solve the problem.
You have to format every Cell on its own, so you have to hook up on the SetCellFormat-Event of every Column:
AddHandler column.SetCellFormat, AddressOf FormatGridRow
In the EventHandler you can check for example the cell value of another column of the same row and change the color of the current cell accordingly. When every cell of the row gets formatted this way, it seems like the row as a whole is formatted.
Private Sub FormatGridRow(ByVal sender As Object, ByVal e As DataGridFormatCellEventArgs)
Dim Cell As DataGridColumnStyle = sender
Dim ColumnStyles As GridColumnStylesCollection = Cell.DataGridTableStyle.GridColumnStyles
Dim columnIndex As Integer = ColumnStyles.IndexOf(ColumnStyles.Item("ColumnName"))
If Cell.DataGridTableTableStyle.DataGrid(e.Row, columnIndex).ToString() = "SomeValue" Then
e.BackBrush = New SolidBrush(Color.Red) 'this does only change the Cell`s background
End If
End Sub

Related

How to set the CheckBox column in DataGridView value to true

GD All,
I've looking around for a solution to my below challenge.
I have got a form with an unbound datagridview, the dg has one added column that allows user to select a method to be used.
The state of the event is stored in a database and after re-opening the form the code checks if the event is in an 'open' state, if so it compares the previously selected method with the methods in the datagrid and should set the previously activated method to be the 'selected' method.
Yet I can't seem to get this to work unfortunately...
The below code loops through the methods in the dg and compares the values, if it meets the methodID it should set the value to 'True' or to the TrueValue anyway.
This is initialized if the database check returns true and after full initialisation of the form, where session.methodID is a field in the returned LINQ query.
For Each r As DataGridViewRow In dgMethods.Rows
If r.Cells(1).Value = session.methodID Then
Dim c As DataGridViewCheckBoxCell = r.Cells(0)
c.Value = c.TrueValue
End If
Next
Unfortunately, this doesn't set the checkbox to 'Checked'.
The loop runs and evaluates the comparison between r.Cells(1).Value and session.methodID correct and triggers correctly.
The interesting thing is if I do a similar loop after the 'CellContentClick' event it does do exactly what is expected. (the example below sets all checkbox values to checked)
Private Sub dgMethods_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgMethods.CellContentClick
'Only single selection allowed, so clear table before submitting new selection
For Each r As DataGridViewRow In dgMethods.Rows
Dim c As DataGridViewCheckBoxCell = r.Cells(0)
c.Value = c.TrueValue
Next
dgMethods.CommitEdit(DataGridViewDataErrorContexts.Commit)
End Sub
So, apparently there is a difference in the state between just calling the loop on the dgMethods and when the dgMethods.CellContentClick event has triggered, yet I do not know which one ?
There are many many post on trying to set the CheckBox column yet I have not been able to get any of them working.
Anybody have any idea ?
I would appreciate your suggestions ?
I was not sure of being undestand your question... but there's s simple way to check and change the state of a chechbox cell in a datagridview:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each dr As DataGridViewRow In DataGridView1.Rows
If CBool(dr.Cells(0).Value) = True Then dr.Cells(0).Value = False : Continue For
If CBool(dr.Cells(0).Value) = False Then dr.Cells(0).Value = True
Next
End Sub
In this example, when you click this button for each row in the datagridview, checks the checkboxcell and set the value to FALSE or TRUE depending of his value.
Hope this helps you.
And let me one more tip. If you get acces to the cells for his name instead of his index use his name, it should helps you avoiding troubles ;)
GD All,
After searching further I came across the following interesting behaviour.
The method selection process is part of a form called 'frmAddEvent', the frmAddEvent form is called from a main form using below routine.
The new form instance is created and afterwards filled using a public sub in the form class called InitializeForm() which uses a GUID parameter to retrieve corresponding data to set the form fields.
If Not (isOpened(rsTankName.unqID)) Then
Dim newForm As New frmAddEvent() '(rsTankName)
newForm.InitializeForm(rsTankName)
newForm.Show()
Else
End If
The initialization sub queries several datatables and sets the corresponding fields in the new form instance correctly if applicable.
Part of that setting is the method selection in the dgMethods datagridview.
It would appear that the sequence in which you call the form makes all the difference as the below code works perfectly:
If Not (isOpened(rsTankName.unqID)) Then
Dim newForm As New frmAddEvent() '(rsTankName)
newForm.Show()
newForm.InitializeForm(rsTankName)
Else
End If
So calling the newForm.InitializeForm(rsTankName)after the newForm.Show event allows the datagridview to set the CheckBoxColumn correctly.
Likely because the actual CheckBox itself is only actually generated upon the Show command, despite the fact that it is 'available' as a cell with DataGridViewCheckBoxColumn properties in the datagrid, directly after the New frmAddEvent has created the new form instance. The actual CheckBox and its corresponding CheckedState is not created before the newForm.Show event is called. It would appear that the when the CheckBox is created for display (during the newForm.Show event) there is no comparison made to its actual value.
So, in order to set the Checkbox column on initiating a new form you have to call the Show event prior to setting the DataGridViewCheckBoxColumn values otherwise the CheckBox will not show it as 'Checked'.

VB.NET - Focus first row and first cell of DataGridView

Good morning,
I have a form with two textbox and a DataGridView.
I'm used to fill my controls then i press Tab to switch to the next one.
However, when i switch from my textbox to my DataGridView, the selected cell is the second one of the first row => DTG.Rows(0).Cells(1).
I need to enter on the DTG.Rows(0).Cells(0) to fill my DTG without using my mouse.
I tried the code bellow :
Public Sub txtBoxTest_Leave() Handles txtBoxTest.Leave
DTG.Focus()
DTG.CurrentCell = DTG(0, 0)
DTG.BeginEdit(True)
End Sub
The cell seems to be selected, but it is not in editmode.
Modify the edit mode to EditOnEnter does not resolve my problem :
DTG.EditMode = DataGridViewEditMode.EditOnEnter
Can someone help me please ?
EDIT :
My datagridview cells are in ReadOnly = False.
Try this:
Dim cell as Windows.Forms.DataGridViewCell= dataGridView1.Rows(0).Cells(0)
DataGridView1.CurrentCell = cell
DataGridView1.BeginEdit(True)

Monitoring Datagridview for rows that are being unhidden

I've got a a bit of code that is allowing a Results box to pop up, populating a DataGridView with information. The DataGridView uses the same BindingSource that another DataGridView uses, so when one is clicked, the other automatically moves to the same selected cell.
The issue I am having is the Result_DataGridView doesn't always contain all of the same rows as the master DGV, as it hides rows that don't match a criteria. If the user clicks on a cell on the Master DGV that isn't present in the Result DGV, the Result DGV un-hides that row (as you can't hide a selected row).
I'm currently trying to use this method to hide the row that appears again, but because of how VB treats "Entering a cell" it fires before the cell actually appears (as it fires on input focus, but before the cell actually appears in the DGV, so that row never gets checked)
Private Sub Result_Datagridview_CellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles Result_Datagridview.CellEnter
Dim Result As Integer
Dim i
For row As Integer = 0 To Result_Datagridview.RowCount - 1
i = row
Result = Array.Find(ResultArray, Function(x) x = Result_Datagridview.Rows(i).Cells(0).Value)
If Result = 0 Then
Result_Datagridview.Rows(i).Visible = False
End If
Next
End Sub
If there was a ".RowsUnhidden" event, this would work fine.
Note - the ResultArray contains all of the index numbers that need to remain visible, the check is performed to see if any rows exist with an index number that does not appear in the array, if so, hide it again.
Does anyone have a work around or better approach to this?
Handling the RowEnter event, you can suspend the binding and reset row.Visible to False.
So, if ResultArray is an Integer array of visible row indices, you simply do the following:
Private Sub Result_Datagridview_RowEnter(sender As Object, e As DataGridViewCellEventArgs)
If Not ResultArray.Contains(e.RowIndex) Then
Dim currencyManager1 As CurrencyManager = DirectCast(BindingContext(Result_Datagridview.DataSource), CurrencyManager)
currencyManager1.SuspendBinding()
Result_Datagridview.Rows(e.RowIndex).Visible = False
currencyManager1.ResumeBinding()
End If
End Sub
You can look at the DataGridView.CellStateChanged event. It occurs when a cell get the focus, lose it, is selected, ...

Select first visible cell of new row in DataGridView

I'm trying to focus input and fire the editing event on each new row that I add to a DataGridView in my form.
This is the code I am trying to user to achieve this.
Private Sub grd_GoldAdders_RowsAdded(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewRowsAddedEventArgs) Handles grd_GoldAdders.RowsAdded
Dim grid As DataGridView = DirectCast(sender, DataGridView)
grid.ClearSelection()
If grid.Rows(e.RowIndex).Cells("grid_flag").FormattedValue = Constants.[New] Then
For Each cell As DataGridViewCell In grid.Rows(e.RowIndex).Cells
If Not cell.Visible Then Continue For
grid.CurrentCell = cell
grid.BeginEdit(False)
Exit For
Next
End If
End Sub
The "grid_flag" is a hidden cell which is used to store custom states for a row.
Prior to adding a row, this is what we see on the form:
This is what we see when we actually try and add a new row:
Notice that both the column 0,0 and the first visible column of the new row are selected, but the column 0,0 has the focus. I do not wish for 0,0 to either get selected or have the focus. I also see here that the row indicator is pointing at row 0 too...
This is how I would like to see things after clicking my Add button:
Does anyone know where I am going wrong with the code? I've searched SO for the most part of the day trying to solve this one.
Instead of using your DataGridView's RowAdded event to set the CurrentCell, add the following code wherever you're adding a new record to your DGV (in your Add button's Click event I assume):
''# Add the new record to your Data source/DGV.
For Each row As DataGridViewRow In grd_GoldAdders.Rows
If row.Cells("grid_flag").FormattedValue = Constants.[New] Then
grd_GoldAdders.CurrentCell = row.Cells("AssySiteColumn") ''# I'm calling the first column in your DGV 'AssySiteColumn'.
grd_GoldAdders.BeginEdit(False)
Exit For
End If
Next
This code simply loops through all the rows in your DGV and specifies as the CurrentCell the first cell in the first row with your Constants.[New] flag value.

How to switch between DataGridViewTextBoxCell and DataGridViewComboBoxCell?

I want to have a DataGridView that has two columns. The first column will always be of type DataGridViewComboBoxColumn. Based on the selection in that column, I'd like to be able to change the corresponding cell in the second column to either a DataGridViewComboBoxCell or a DataGridViewTextBoxCell.
I'm thinking I just need to make the second column of type DataGridViewColumn, but don't understand the mechanics of how to change the cell type on the fly.
I'm working with VB.NET in Visual Studio 2005.
Thanks in advance!
Update: One way around it, I suppose, is to make the second column as a DataGridViewComboBoxColumn, and change the attributes of the cell so that it either behaves like a drop-down list, or as an (editable) drop-down with no elements. The latter looks enough like a text box that I could live with it, and it wouldn't involve changing the type of the cell.
I don't have the VB.Net version,but hopefully this quick C# snippet will help you or point you in the right direction.
In this example, I set up a simple DataGridView with 2 columns. The first being a DataGridViewComboBox populated with two choices: "Text" or "Combo".
The second column is initially set to DataGridViewTextBoxColumn from the designer.
I handle the CurrentCellDirtyStateChanged event on the DataGridView. I check if the cell is dirty and only check the first column (The ComboBox). You gotta call the CommitEdit to get the new value in the combo or else you will be looking at the previous value. Based on the selection in the combo box I then overwrite the cell in the 2nd column with a new cell of that type.
You would add your own logic (populate the drop downs and handle the value). You might want to store the value and then put it back into the cell or whatever.
Here is the code I used and did a quick and dirty test on:
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty == false)
{
return;
}
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
if (dataGridView1.CurrentCell.ColumnIndex == 0)
{
if (((string)dataGridView1.CurrentCell.Value) == "Text")
{
dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1] = new DataGridViewTextBoxCell();
}
else if (((string)dataGridView1.CurrentCell.Value) == "Combo")
{
dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1] = new DataGridViewComboBoxCell();
}
}
}
Here is a quick VB translation, that I tested and works.
Public Class Form1
Private Sub DataGridView1_CurrentCellDirtyStateChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged
If DataGridView1.IsCurrentCellDirty = False Then
Return
End If
DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
If DataGridView1.CurrentCell.ColumnIndex = 0 Then
If CStr(DataGridView1.CurrentCell.Value) = "Text" Then
DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).Cells(1) = New DataGridViewTextBoxCell
ElseIf CStr(DataGridView1.CurrentCell.Value) = "Combo" Then
DataGridView1.Rows(DataGridView1.CurrentCell.RowIndex).Cells(1) = New DataGridViewComboBoxCell
End If
End If
End Sub
End Class
You will lose any value stored in that column, so you would need to save it first.
Jon
You can create your own cell template that hosts a user control. In the user control you add a textbox and a combobox, and add a method/property to show one and hide another.
This sample creates a radio button cell, it is not hard to change the code to host a user control.
dgvCell = new DataGridViewTextBoxCell(); // code to remove checkbox
dgvCell.Value = string.Empty;
dgv_modi_del_trans.Rows[1].Cells[0] = dgvCell;