I was trying to Change the row color in DataGridView based on the quantity of a cell value but first row doesn't change [duplicate] - vb.net

I am using vb.net and I have data coming into my DGV and I have a column labeled deployed if it's a '1', I want to have all the rows with '1' in the deployed column RED and if it's a '0', I want all the rows to be GREEN. This is my method I have, right now the column is the 10th column but it doesn't like the = operator. Even when I use quotes on the 1 with equals compare operator for strings. Should be an integer but I was trying every way I could to see why it's not working.
Private Sub LaptopGrid_CellFormatting(ByVal Sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles LaptopGrid.CellFormatting
For i As Integer = 0 To LaptopGrid.Rows.Count - 1
If LaptopGrid.Rows(i).Cells(9).Value = 1 Then
LaptopGrid.RowsDefaultCellStyle.BackColor = Color.Green
End If
Next
End Sub

There are a couple of issues with your code.
First, you are handling the CellFormatting event but you are iterating every row to set the backcolor. That event is meant for you to do something to a single, specific cell, the one in question is indicated in the event args: e.RowIndex and e.ColumnIndex. Using a loop, you are acting on many more rows than needed and doing so over and over.
Second, VB has data types. Int32 is one type, String is another, and Object is yet another. You need to convert one type to the other type before you compare. LaptopGrid.Rows(r).Cells(c).Value returns Object (since a cell can literally hold anything), so to compare to 1 you need to convert it to integer.
Finally, you may not want the CellFormatting event for this. If the cell in question is not on screen, the event wont fire (perhaps the user resized the columns). RowPrePaint on the other hand will fire when the row scrolls into view.
Private Sub dgv1_RowPrePaint(sender As Object,
e As DataGridViewRowPrePaintEventArgs) Handles dgv1.RowPrePaint
' dont do the NewRow
If e.RowIndex < 0 OrElse dgv1.Rows(e.RowIndex).IsNewRow Then Return
' convert to int32, then compare
' act on just this row - e.RowIndex
If Convert.ToInt32(dgv1.Rows(e.RowIndex).Cells(3).Value) > 3 Then
dgv1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.LemonChiffon
Else
dgv1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.MistyRose
End If
End Sub
If the user can edit that cell value, you will want to update the back color accordingly.

Related

DataGridView select only certain number of column vb.net

I have DataGridView1 that contain n number of column i want user to select the column that he want to save then i save it ..(done)
The problem here that i want the user to select only 3 column and on four column give user massage that he/she have to select only three.
To unselect the last one i use DataGridView1_ColumnHeaderMouseClick Event and I present the message but can not find anything like DataGridView1.SelectColumn = False
If DataGridView1.SelectedColumns.Count > 3 Then
MsgBox("You have to choose 3 columns only")
Exit Sub
End If
I'm not convinced you can count the selected columns that way. Anyway, here's a way to use the args of the event to achieve what I think you're trying to achieve:
Private Sub DataGridView1_ColumnHeaderMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.ColumnHeaderMouseClick
If DataGridView1.Columns.GetColumnCount(DataGridViewElementStates.Selected) > 3 Then
MsgBox("You cannot select more than 3 columns.")
DirectCast(sender, System.Windows.Forms.DataGridView).Columns(e.ColumnIndex).Selected = False
End If
End Sub
I used a DirectCast to get the sender to behave as the datagridview (which it is) because this way I could attach this event to several different dtagridviews, but if you dislike that form you can always use DataGridView1.Columns(e.ColumnIndex).Selected = False instead.
Also, I use the e.ColumnIndex to unselect the last column the user clicked on because I though that it was what you were trying to do, but you can change this comportment for something more suitable to your needs as you now know how to unselect columns.
Have fun!

DataGridView flickering issue [duplicate]

I am using vb.net and I have data coming into my DGV and I have a column labeled deployed if it's a '1', I want to have all the rows with '1' in the deployed column RED and if it's a '0', I want all the rows to be GREEN. This is my method I have, right now the column is the 10th column but it doesn't like the = operator. Even when I use quotes on the 1 with equals compare operator for strings. Should be an integer but I was trying every way I could to see why it's not working.
Private Sub LaptopGrid_CellFormatting(ByVal Sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles LaptopGrid.CellFormatting
For i As Integer = 0 To LaptopGrid.Rows.Count - 1
If LaptopGrid.Rows(i).Cells(9).Value = 1 Then
LaptopGrid.RowsDefaultCellStyle.BackColor = Color.Green
End If
Next
End Sub
There are a couple of issues with your code.
First, you are handling the CellFormatting event but you are iterating every row to set the backcolor. That event is meant for you to do something to a single, specific cell, the one in question is indicated in the event args: e.RowIndex and e.ColumnIndex. Using a loop, you are acting on many more rows than needed and doing so over and over.
Second, VB has data types. Int32 is one type, String is another, and Object is yet another. You need to convert one type to the other type before you compare. LaptopGrid.Rows(r).Cells(c).Value returns Object (since a cell can literally hold anything), so to compare to 1 you need to convert it to integer.
Finally, you may not want the CellFormatting event for this. If the cell in question is not on screen, the event wont fire (perhaps the user resized the columns). RowPrePaint on the other hand will fire when the row scrolls into view.
Private Sub dgv1_RowPrePaint(sender As Object,
e As DataGridViewRowPrePaintEventArgs) Handles dgv1.RowPrePaint
' dont do the NewRow
If e.RowIndex < 0 OrElse dgv1.Rows(e.RowIndex).IsNewRow Then Return
' convert to int32, then compare
' act on just this row - e.RowIndex
If Convert.ToInt32(dgv1.Rows(e.RowIndex).Cells(3).Value) > 3 Then
dgv1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.LemonChiffon
Else
dgv1.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.MistyRose
End If
End Sub
If the user can edit that cell value, you will want to update the back color accordingly.

vb.net - Sort datagridview column numerically

I know this has been asked quite a few times, but i'm having issues with the solutions found on most other pages.
I have a single datagridview column that i want to be sorted by number (1,2,10 instead of 1,10,2)
Best i can see online, i need to convert the column or cell to an integer value type - but i'm not sure how to do so.
I've tried grid.columns(4).valuetype = typeof(System.int32), and tried the same for cells individually.
Trying above always results in a "int32 is a type in 'system' and cannot be used as an expression" error - which i'm not sure about.
The data itself is obtained froma text file, and converted from string to integer when being added into the cell datagrid_alltracks.Rows(shutupaboutlambda).Cells(4).Value = CInt(numstring))
You can just set the DataGridView SortCompare Event to compare two integers (or two singles, or two doubles). Code wise (calling your datagridview "grid")
Private Sub grid_SortCompare(sender as Object, e as DataGridViewSortCompareEventArgs) Handles grid.SortCompare
e.SortResult = CInt(e.cellvalue1).CompareTo(CInt(e.cellValue2))
e.Handled = True
End Sub
if you are doing single or double variables, use CSng or CDbl instead of CInt
e.SortResult = CSng(e.cellvalue1).Compareto(CSng(e.CellValue2)
You can do more fancy sorting if you want, You basically need to know that e.SortResult is Positive, Negative or Zero, and your cells are sorted according to that result (Positive keep order, negative reverse order, Zero - matched - do nothing (yet)). The current row index(s) and column are available in the e arguments so you can also compare adjacent column data if the current cells are matched)
If the grid is bound to a data source you could try
datatable.Columns.Add("ColumnName", GetType(Integer))
Else you may need to use the SortCompare event on the gridview.
See here
I know I'm coming to the party late, but I found that I once I had added the data, I needed to convert the desired columns to have a data type.
I'm adding data like the following:
DataGridView1.Rows.Add(New String() {CInt(recordnum), True, "play", wszName.ToString, qiOffset.ToString, value.ToString, qiLength.ToString})
Then, after all the data has been added, I then do a simple loop and convert the column, where I can then sort it. It's set up so you can do multiple columns if need be.
Dim colnum As Integer
colnum = 0 ' set this as your column to change the data type to
For i As Integer = 0 To DataGridView1.Rows.Count - 1
Dim d As Double = Double.Parse(DataGridView1.Rows(i).Cells(colnum).Value.ToString())
DataGridView1.Rows(i).Cells(colnum).Value = CInt(d)
DataGridView1.Rows(i).Cells(colnum).ValueType = GetType(Double)
Next
Sorting can work for whatever column you adjusted. In this case, it's column 4.
DataGridView1.Sort(DataGridView1.Columns(4), System.ComponentModel.ListSortDirection.Ascending)

Datagridview show date or time (VB.NET)

I have a datagridview in which some columns where initially specified as String and they contain date or time, depending on some bussiness logic.
I am changing the type of the column (to datetime) to allow correct sorting. And I would like to know if it is possible to show date values or time values depending on the row. Or I will always have to show both.
Thank you.
You can handle the CellFormatting event. This event is fired everytime a cell is painted. You can change what value is being displayed without changing the underlying value and the format of the cell.
By doing this you can change the format depending on the row and column
Private Sub CellFormatting_EventHandler(sender As Object, e As DataGridViewCellFormattingEventArgs)
If e.ColumnIndex = 2 AndAlso CType(sender, DataGridView)(5, e.RowIndex).Value.ToString = "Steve" Then 'Or whatever logic you like
e.Value = CType(e.Value, Date).ToShortTimeString
End If
End Sub

Subtraction using 1 textbox visualbasic

Could someone please check my code? i don't seem to get the correct answer after the initial run of my code.
i want it would be like.
5-1=4 then if i press the minus button again and i want the new value of my textbox to be subtracted from the difference which in case is 4.
i'm getting the right answer from the 1st process but not when i want to subtract another value from my difference.
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If C <> 0 Then
Dif = C - Val(TextBox1.Text)
C = Dif
Label1.Text = Dif
TextBox1.Clear()
End If
C = Val(TextBox1.Text)
TextBox1.Clear()
End Sub
I don't know what you're trying to accomplish exactly, but there are several problems with your code. Unless it's initialized elsewhere, the first time you click Button2 the variable 'C' is zero, so the 'If' instruction is ignored, C gets the value from the textbox and then clears the textbox.
On a second click C has value (assuming that textbox wasn't empty in the first place) and then you substract the content of Textbox1 (assuming it has something) from the value of 'C', and then display it into a label.
Wouldn't it be simpler to assign the contents of TextBox1 and TextBox2 to two variables (checking in the process to see if those contents are valid, i.e. numeric) and then display the result of substracting both variables into Label1?