create labels on a form based on entries in datagridview vb.net - vb.net

I have a form with a datagridview containing entries for an invoice. I have created a separate form that will contain the entries from the datagridview in labels. Unfortunately, I am having trouble finding out how to generate a table of labels with each label holding the value of the corresponding entry in the datagridview. I am wondering if it is possible to do this with a for next loop based on the number of rows in the datagridview. Thanks in advance for any guidance in this!

Dim lbl As New Label
With lbl
.Text = txtCaption ' value you want it to display from dgv.dr
.Top =
.Left =
.Name =
.Size =
End With
I dont know what you mean by a table of labels, so lets say you want to add them to a panel there just for them:
pnlLabels.Controls.Add(lbl)
Make that a Sub and call it from the loop processing the rows in the datagridview, passing the relevant value for its caption. Something like this:
CreateLabel(ndx as Integer, txtCaption as String)
You will need an index or counter of how many made so that some properties like .Top can be offset accordingly.
EDIT
I have no idea what your dgv or data etc looks like, but your loop would be SOMETHING like this:
pnlLabels.Controls.Clear ' might want to remove any old ones
Dim Caption as String = ""
Dim ndx As Integer = 0
For Each dr As DataGridViewRow in dgv.rows
Caption = dr.Cells(X) ' or where the data is
CreateLabel(ndx, Caption)
ndx += 1
Next

Related

How toI convert a Data gridview column to a list of strings?

I'm trying to convert the first column from a Data Grid View to a list of string, then search through the list and highlight the corresponding row in red.
This is what I currently have
Dim search As String = txtsearch.Text
Dim lsttitlesort As New List(Of String)()
For i = 0 To dgvbooks.Rows.Count - 1
lsttitlesort.Add(dgvbooks(0, i).Value)
Next
For i As Integer = 1 To lsttitle.Count - 1
If lsttitlesort(i).ToLower.Contains(search.ToLower) Then
dgvbooks.Rows(i).DefaultCellStyle.BackColor = Color.Red
End If
Next
The problem is that when I try to run it, it crashes and displays an error message saying
System.NullReferenceException: 'Object reference not set to an instance of an object.'
I'm new to Data Grid Views: can you explain me how to fix it?
You can search directly on the DataGridView without using a list:
Dim search As String = txtsearch.Text
'iterate through all rows of the DataGridView to search the value.
For Each dgrBook As DataGridViewRow In dgvbooks.Rows
'you can skip the new row at the end (if available).
If dgrBook.IsNewRow Then
Continue For
End If
'check if first column contains the search value.
'if search value found on first column set the background color to red,
'otherwise reset the background to white.
If CStr(dgrBook.Cells(0).Value & "").ToLower.Contains(search.ToLower) Then
dgrBook.DefaultCellStyle.BackColor = Color.Red
Else
dgrBook.DefaultCellStyle.BackColor = Color.White
End If
Next

How to fill a combobox in a datagridview

I have a datagrid view with 10 columns. It includes 2 checkbox columns followed by a combobox and then a number of text boxes for data entry. I do not have a database to load the combobox drop down but I do have a variable with 19 rows. I have tried a number of methods from SO but haven't been able to get this to work correctly so I can load the combobox for the user to select a value.
The code I've been using is like this. I have tried several different ways that are commented out as well...
' Build datagridview row
'
Dim t1 As New DataTable
For Each col As DataGridViewColumn In dgvMultiSelect.Columns
t1.Columns.Add(col.HeaderText)
Next
Dim dgvcb As New DataTable
dgvcb.Columns.Add("RunID", GetType(String))
For el = 0 To sRunID.Length - 1
dgvcb.Columns.Add(sRunID(el))
RunID.Items.Add(sRunID(el))
Next
' RunID.DataSource = dgvcb
' RunID.DataPropertyName = "dgvcb"
' RunID.DataSource = sRunID
' RunID.DataPropertyName = "sRunID"
'Dim chk As New DataGridViewCheckBoxColumn()
'DataGridView1.Columns.Add(chk)
'chk.HeaderText = "Check Data"
'chk.Name = "chk"
dgvMultiSelect.Rows(0).Cells(0).Value = True
The checkbox works fine (it shows as checked) and I was able to set the combobox value to show but clicking on the dropdown does nothing. I believe the data is in RunID (the column in the dgv.
Well, the answer that worked for me is: I was referencing the datagridviewCOLUMN and not a datagridviewCOMBOBOXcolumn. Thanks to Sai Kalyan Kumar Akshinthala!
' Build datagridview row
Dim dgvcc As DataGridViewComboBoxColumn
dgvcc = dgvMultiSelect.Columns("RunID")
For el = 0 To sRunID.Length - 1
dgvcc.Items.Add(sRunID(el))
dgvMultiSelect.Rows(0).Cells(2).Value = sRunID(el)
Next
Maybe next time you'll try to understand before voting down. Such a silly thing this voting down anyway. It should not reduce reputation.

First 30 % displayed columns in DataGridView

First of all: 30% doesn't matter. That's a question of design. We can also say the first 3 Displayed Columns.
In my DataGridView I am using BackgroundColors for Rows to pass the User some information.
To keep this information visible to the user while Rows are being selected the first 30% of the columns should get the same SelectionBack/ForeColor as the Back/ForeColor.
So far that has never been a problem using
.cells(0).Style.SelectionBackColor = .cells(0).Style.Backcolor
(and so on).
Now I added the function that allows the user to reorder the Columns which makes the following Statement become true:
ColumnIndex != DisplayedIndex.
That statement beeing true makes the SelectionBackColor-Changed cells be somewhere mixed in the row and not in the first columns anymore. It still does the job, but looks terrible.
Is there something like a "DisplayedColumns" collection in order of the .DisplayedIndex Value that i could use to call the first few DisplayedColumns? If not, how could I effectivly create one my own?
Edit:
The user can also hide specific columns, that do not matter for him. So we have to be aware of Column.DisplayedIndex and Column.Visble
Got it working with the following code:
Try
' calculate what is thirty percent
Dim colcount As Integer = oDic_TabToGridview(TabPage).DisplayedColumnCount(False)
Dim thirtyPercent As Integer = ((colcount / 100) * 30)
' Recolor the first 30 % of the Columns
Dim i As Integer = 0
Dim lastCol As DataGridViewColumn = oDic_TabToGridview(TabPage).Columns.GetFirstColumn(DataGridViewElementStates.Visible)
While i < thirtyPercent
.Cells(lastCol.Index).Style.SelectionBackColor = oCol(row.Item("Color_ID") - 1)
.Cells(lastCol.Index).Style.SelectionForeColor = Color.Black
lastCol = oDic_TabToGridview(TabPage).Columns.GetNextColumn(lastCol, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
i += 1
End While
Catch ex As Exception
MsgBox(ex.Message & vbNewLine & ex.StackTrace)
End Try
Let us first assume you are coloring your rows somehow resembling the following manner:
Me.dataGridView1.Rows(0).DefaultCellStyle.BackColor = Color.PowderBlue
Me.dataGridView1.Rows(1).DefaultCellStyle.BackColor = Color.Pink
' ...etc.
In the DataGridView.CellPainting event handler, you can determine if the painting cell falls within the first N columns by utilizing the DataGridViewColumnCollection.GetFirstColumn and DataGridViewColumnCollection.GetNextColumn methods.
If the cell belongs to one these columns, set the cell's SelectionBackColor to the cell's BackColor. Otherwise set it to the default highlighting color.
Dim column As DataGridViewColumn = Me.dataGridView1.Columns.GetFirstColumn(DataGridViewElementStates.Visible)
e.CellStyle.SelectionBackColor = Color.FromName("Highlight")
' Example: Loop for the first N displayed columns, where here N = 2.
While column.DisplayIndex < 2
If column.Index = e.ColumnIndex Then
e.CellStyle.SelectionBackColor = e.CellStyle.BackColor
Exit While
End If
column = Me.dataGridView1.Columns.GetNextColumn(column, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
End While
As a side note: You may want to consider changing the ForeColor on these cells for readability - depending on your row's BackColor choices. Likewise, if only a single cell is selected from one these first N columns, it can be difficult to notice.

Control name from Variable or Dataset. (Combobox)(.items.add)(.datasource)

I've checked for hours but I can't seem to find anything to help.
I want to loop through tables and columns from a dataset and use the column name in a combobox.items.add() line, however the eventual goal is to fill the combobox from the dataset itself possibly in a combobox.datasource line.
The first problem is that I can't get the code correct to setup the combobox control where it allows me to use .items.add("") and in extension .datasource
Error Message = "Object reference not set to an instance of an object"
dstcopt is the dataset from a oledbDataAdapter .fill(dstcopt,"table") line (which returns correct values)
tc_opt is a tab name on a tab control where the comboboxes are
For Each dstable In dstcopt.Tables
For Each dscolumn In dstable.Columns
Dim colName As String = dscolumn.ToString
MsgBox(colName) 'This retuns "aantigen"
Dim cb As ComboBox = Me.tc_opt.Controls("cb_" & colName)
cb.Items.Add(colName)
'cb_aantigen.DataSource = dstcopt.Tables(dstable.ToString)
'cb_aantigen.DisplayMember = "aantigen"
'cb_atarget.DataSource = dstcopt.Tables(dstable.ToString)
'cb_atarget.DisplayMember = "atarget"
Next
Next
The second problem comes when I do it manually (which works) using the exact combobox names cb_aantigen and cb_atarget as seen in the comments.
The problem is that once the form is loaded and the cb's are filled with the correct values, I can't change the value in any single cb individually, when I change one value it changes them all (there is 15 comboboxes in total) I know this is down to using a dataset, but I don't know away to 'unlink them from each other or the dataset'
Not sure if I need to split this into 2 questions, but help on either problem would be appreciated.
EDIT:
After looking at only this section of code for a day. This is what I have come up with to tackle both the problems at once.
The combobox control not working was down to using a tab tc_opt instead of a groupbox gp_anti
The issue with splitting the dataset up into individual comboboxes, I've worked around by taking the value of each cell in the database and adding it separately, probably a better way to do it though
For Each dstable As DataTable In dstcopt.Tables
For Each dscolumn As DataColumn In dstable.Columns
Dim colName As String = dscolumn.ToString
Dim cb(2) As ComboBox
cb(0) = CType(Me.gp_anti.Controls("cb_" & colName), ComboBox)
cb(1) = CType(Me.gp_rec.Controls("cb_" & colName), ComboBox)
cb(2) = CType(Me.gp_nat.Controls("cb_" & colName), ComboBox)
For icb = 0 To cb.Count - 1
If Not (IsNothing(cb(icb))) Then
For irow = 0 To dstable.Rows.Count - 1
If dstable.Rows(irow)(colName).ToString <> Nothing Then
Dim icbitemdupe As Boolean = False
If cb(icb).Items.Contains(dstable.Rows(irow)(colName).ToString) Then
icbitemdupe = True
End If
If icbitemdupe = False Then
cb(icb).Items.Add(dstable.Rows(irow)(colName).ToString)
End If
End If
Next
End If
Next
Next
Next

Make particular column as combo box of DataGridView

I just want to make Data Grid. Where first and second column of data grid is for storing single value and third column as combo box.
The code that i tried is
Dim productGrid As New DataGridView
ProductGrid.Columns(0).Name = "CB"
ProductGrid.Columns(1).Name = "ProductGroup"
ProductGrid.Columns(2).Name = "Product"
Dim i As Integer
With ProductGrid
If .Rows.Count = 0 Then Exit Sub
i = 1
Dim objValueItems As New DataGridViewComboBoxCell
objValueItems.Items.Add("Server")
objValueItems.Items.Add("Standalone")
objValueItems.Items.Add("Demo")
objValueItems.Items.Add("Anywhere")
ProductGrid.Item(2, i).Value = objValueItems
End With
I am getting the error on "ProductGrid.Item(2, i).Value = objValueItems" this line. Error is " Index was out of range.
Bear in mind that all the cells of a ComboBox DGV Column have the same contents, thus you are not assigning a list of items to a given cell, but to all of them (to a column). You have to include this when adding the given column. Sample code:
Dim productGrid As New DataGridView
With productGrid
.Columns.Add("CB", "CB") 'Text-type column
.Columns.Add("ProductGroup", "ProductGroup") 'Text-type column
Dim objValueItems As New DataGridViewComboBoxColumn
With objValueItems
.Name = "Product"
.Items.Add("Server")
.Items.Add("Standalone")
.Items.Add("Demo")
.Items.Add("Anywhere")
End With
.Columns.Add(objValueItems) 'ComboBox-type column
End With