Control Event (Changed) In DataTable - vb.net

Helo:
How to overcome the problem of [RowChanged] event within the [DataTable] in the [DataGridView].
Explanation: You have created a column in the dataTable to find out which rows have been modified, in order to facilitate the knowledge of these rows to update them in the database, but the problem in the event(Row_Changed), can not be explained by more words in the code, see the column of (ISCHANGE) after modifying any row and cover the The Save button you find takes the value True and then False;
Public Class Class1
Public Table As DataTable
Sub New()
Table = New DataTable
Table.Columns.Add("IsChange", System.Type.GetType("System.Boolean"))
Table.Columns.Add("TeacherName", System.Type.GetType("System.String"))
Table.Columns("IsChange").DefaultValue = False
Dim dr As DataRow = Table.Rows.Add
dr("TeacherName") = "X1"
dr = Table.Rows.Add
dr("TeacherName") = "X2"
dr = Table.Rows.Add
dr("TeacherName") = "X3"
dr = Table.Rows.Add
AddHandler Table.RowChanged, New DataRowChangeEventHandler(AddressOf Row_Changed)
End Sub
Sub New(SourceDataTable As DataTable)
'Import DataTable
Table = SourceDataTable
End Sub
Public Sub Save()
GotoChange = False 'disable the event (Row_Changed)
For ALoop As Integer = 0 To Table.Rows.Count - 1
'=======================================
'Here Code Save To DataBase
'
'
'=======================================
Table(ALoop)("IsChange") = False 'RowChanged =False
Next
GotoChange = True 'Enabled the event (Row_Changed)
End Sub
Dim GotoChange As Boolean = True 'This variable is to disable the event (Row_Changed)
Private Sub Row_Changed(ByVal sender As Object, ByVal e As DataRowChangeEventArgs)
If Not GotoChange Then Exit Sub
If e.Action = DataRowAction.Add Or e.Action = DataRowAction.Change Then
If CBool(e.Row("IsChange")) = False Then
MsgBox("IsChange")
e.Row("IsChange") = True 'If [True] this means that the row has been changed
End If
End If
End Sub
End Class
Form Code :
Change Any Row Then Button Save:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim A As New Class1
Me.DataGridView1.DataSource = A.Table
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim A As New Class1(Me.DataGridView1.DataSource)
'Change Value Any Row Then Button Save
'Here Problem: Show Column(IsChang) After Save
'The value First (False) Then (True)
A.save()
End Sub
End Class

Related

Datagridview form always open with row in selected state

I have two forms: frmMain and frmProduct
In the main form frmMain, I have a Datagridview1 and the buttons: tsbInsert_click, tsbAlter_click and tsbConsult_click.
When I open the main form frmMain, there is still no row in the Datagridview1 and when I click on any of the tsbAlter_click or tsbConsult_click buttons, the code displays the message "Select a product", which is correct , because there is still no product created in the register.
When I click on the tsbInsert_click button, the code opens the frmProduct to insert a record in the register and then returns to the main form frmMain, which, in the line of the Datagridview1, shows the record that was included.
The problem is that when I include a record in the register, the Datagridview1 ALWAYS returns with the state of the selected row, and the condition If DGProducts.CurrentRow Is Nothing is never true again ... so when I click on tsbAlter_click or tsbConsult_click, the "Select a product" message no longer appears and it should have since I didn't select any rows in Datagridview1.
frmMain Code:
Public Class frmMain
Private Sub tsbInsert_Click(sender As Object, e As EventArgs) Handles tsbInsert.Click
Using frm As New frmProduct("Insert", "")
frm.ShowDialog()
If frm.txtPrdCod.Text <> "" Then
DGProducts.Rows.Add(Campo(0), Campo(1), Campo(2))
End If
End Using
End Sub
Private Sub tsbAlter_Click(sender As Object, e As EventArgs) Handles tsbAlter.Click
If DGProducts.CurrentRow Is Nothing Then
MessageBox.Show("Select a product")
Exit Sub
End If
Dim codProd As String = DGProducts.CurrentRows.Cells("prdCod").Value
Using frm As New frmProduct("Alter", codProd)
frm.ShowDialog()
With DGProducts.Rows(DGProds.CurrentCell.RowIndex)
.Cells("prdCod").Value = Field(0)
.Cells("prdName").Value = Field(1)
.Cells("prdManufac").Value = Field(2)
End With
End Using
End Sub
Private Sub DGProducts_CellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles DGProducts.CellEnter
With DGProducts.Rows(DGProducts.CurrentCell.RowIndex)
Campo(0) = .Cells("prdCod").Value
Campo(1) = .Cells("prdName").Value
Campo(2) = .Cells("prdManufac").Value
End With
End Sub
End Class
frmProduct code:
Public Class frmProduct
Private Sub frmProduct_Load(sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If _operation = "Alter" Then
txtPrdCod.Text = Campo(0)
txtPrdName.Text = Campo(1)
txtManufct.Text = Campo(2)
Else
txtPrdCod.Text = ""
txtPrdName.Text = ""
txtManufct.Text = ""
Enf If
End Sub
Dim _operation As String
Dim _codProd As String
Public Sub New(operation As String, codProd As String)
InitializeComponent()
Select Case operation
Case "Insert"
_operation = operation
Case "Alter"
_operation = operation
_codProd = codProd
Case Else
MessageBox.Show("Invalid option!")
Close()
End Select
End Sub
Private Sub tsbRecord_Click(sender As Object, e As EventArgs) Handles tsbRecord.Click
Field(0) = txtPrdCod.Text
Field(1) = txtPrdName.Text
Field(2) = txtManufct.Text
Me.Close()
End Sub
End Class
How do I make it so that when I add a product to the register, Datagridview1 DOES NOT return with the line in the SELECTED state and the message "Select a product" appears when I don't select a line from Datagridview1?
The command DGProducts.Rows.Add(Field(0), Field(1), Field(2)), automatically changes the value DGProducts.SelectedRows.Count to 1, so I set DGProducts.CurrentCell = Nothing after command DGProducts.Rows.Add in code:
Private Sub tsbInsert_Click(sender As Object, e As EventArgs) Handles tsbInsert.Click
Using frm As New frmProduct("Insert", "")
frm.ShowDialog()
If frm.txtPrdCod.Text <> "" Then
DGProducts.Rows.Add(Campo(0), Campo(1), Campo(2))
DGProducts.CurrentCell = Nothing
End If
End Using
End Sub

Datagridview filter from textbox

i have a vb.net datagridiew and i fill my datagridview add manuel rows
I read too many questions about this questions and answers, but i could't find my answer.
Dim I = .Rows.Add
.Rows(I).Cells(0).Value = "AA"
for example;
COLUMN1 COLUMN2
AA 1
BB 2
so i want filter datagridview from textbox1.text change
What i tried;
TryCast(dgv1.DataSource, DataTable).DefaultView.RowFilter = "COLUMN1 LIKE '%A%'"
Implementation as per comment by #Jimi
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
BindGrid()
End Sub
Private Sub BindGrid()
Dim dt As New DataTable
dt.Columns.Add("Column1", GetType(String))
dt.Columns.Add("Column2", GetType(Integer))
DataGridView1.DataSource = dt
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
TryCast(DataGridView1.DataSource, DataTable).DefaultView.RowFilter = "COLUMN1 LIKE '%A%'"
End Sub
Create a class which represents a single row.
Public Class MyRow
Public Property Name As String
Public Property Value As Integer
End Class
Set collection of rows to the DataSource fo the DataGridView
Private _rows As List(Of MyRow)
Private Sub Form_Load()
_rows = New List(Of MyRow) From
{
New MyRow With { .Name = "AA", .Value = 1 },
New MyRow With { .Name = "BB", .Value = 2 }
}
myDataGridView.DataSource = _rows
End Sub
Every time value changed in textbox filter collection and set filtered result to the DataSource
Private Sub TextChanged(sender As Object, e As EventArgs) Handles txt.TextChanged
Dim textbox = DirectCast(sender, TextBox)
myDataGridView.DataSource = _rows.
Where(Function(row) row.Name.Contains(textbox.Text)).
ToList()
End Sub
i added second datagridview because in one datagridview always zero record found
Sub DATA_TABLE()
Dim dt As DataTable = New DataTable
Dim dr As DataRow
For COL = 0 To EARSIV_TABLO.ColumnCount - 1
dt.Columns.Add(EARSIV_TABLO.Columns(COL).HeaderText)
Next
For i = 0 To EARSIV_TABLO.RowCount - 1
dr = dt.NewRow()
For COL = 0 To EARSIV_TABLO.ColumnCount - 1
dr(COL) = EARSIV_TABLO.Rows(i).Cells(COL).Value
Next
dt.Rows.Add(dr)
Next
DGV1.DataSource = ""
DGV1.DataSource = dt
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
TryCast(DGV1.DataSource, DataTable).DefaultView.RowFilter = "UNVAN LIKE '%" & TextBox1.Text & "%'"
End Sub

How to show records added to datagridview in real time

A co-worker needs to search our network and her File Explorer search does not work well. I threw this app together quickly to allow her to search and it works well. The results are written to a datagridview, but the results are not shown until the search is complete.
I would like the datagridview to show records as they are added and allow her to cancel the search if she wants.
Using a backgroundworker, I tried to refresh the grid, but as soon as it finds a match, the code stops running. There are no errors, it just stops running.
So how can I get the grid to update as it continues to search?
Public dtResults As DataTable
Dim myDataSet As New DataSet
Dim myDataRow As DataRow
Dim colType As DataColumn
Dim colResult As DataColumn
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
dtResults = New DataTable()
colType = New DataColumn("Type", Type.GetType("System.String"))
colResult = New DataColumn("Search Result", Type.GetType("System.String"))
dtResults.Columns.Add(colType)
dtResults.Columns.Add(colResult)
DataGridView1.DataSource = dtResults
DataGridView1.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
btnSearch.Enabled = False
sbStatusBar.Text = "Searching..."
dtResults.Clear()
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
LoopSubFolders(txtSearchLocation.Text)
End Sub
Public Sub LoopSubFolders(sLocation As String)
Dim di = New DirectoryInfo(sLocation)
Dim mySearchterm As String = LCase(txtSearchTerm.Text)
Dim fiArr As FileInfo() = di.GetFiles()
Dim sSearchTarget As String
sbStatusBar.Text = "Searching " & sLocation
'Search File names in
If cbFileNames.Checked = True Then
For Each myFile In fiArr
sSearchTarget = LCase(myFile.Name)
If sSearchTarget.Contains(mySearchterm) Then
myDataRow = dtResults.NewRow()
myDataRow(dtResults.Columns(0)) = "File"
myDataRow(dtResults.Columns(1)) = Path.Combine(sLocation, myFile.Name)
dtResults.Rows.Add(myDataRow)
End If
Next
End If
For Each d In Directory.GetDirectories(sLocation)
If cbFolderNames.Checked = True Then
sSearchTarget = LCase(d)
If sSearchTarget.Contains(mySearchterm) Then
myDataRow = dtResults.NewRow()
myDataRow(dtResults.Columns(0)) = "Folder"
myDataRow(dtResults.Columns(1)) = d
dtResults.Rows.Add(myDataRow)
End If
End If
LoopSubFolders(d)
Next
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
btnSearch.Enabled = True
sbStatusBar.Text = "Complete"
DataGridView1.DataSource = Nothing
DataGridView1.DataSource = dtResults
DataGridView1.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End Sub
Here's an example of how you might do it using the suggested ReportProgress method and ProgressChanged event:
Private table As New DataTable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Configure table here.
DataGridView1.DataSource = table
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Setup UI here.
'Note that you MUST pass in the TextBox data as you MUST NOT touch the UI directly on the secondary thread.
BackgroundWorker1.RunWorkerAsync({TextBox1.Text, TextBox2.Text})
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
'Get the data passed in and separate it.
Dim arguments = DirectCast(e.Argument, String())
Dim folderPath = arguments(0)
Dim searchTerm = arguments(1)
SearchFileSystem(folderPath, searchTerm)
End Sub
Private Sub SearchFileSystem(folderPath As String, searchTerm As String)
For Each filePath In Directory.GetFiles(folderPath)
If filePath.IndexOf(searchTerm, StringComparison.InvariantCultureIgnoreCase) <> -1 Then
'Update the UI on the UI thread.
BackgroundWorker1.ReportProgress(0, {"File", filePath})
End If
Next
For Each subfolderPath In Directory.GetDirectories(folderPath)
If subfolderPath.IndexOf(searchTerm, StringComparison.InvariantCultureIgnoreCase) <> -1 Then
'Update the UI on the UI thread.
BackgroundWorker1.ReportProgress(0, {"Folder", subfolderPath})
End If
SearchFileSystem(subfolderPath, searchTerm)
Next
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
'Get the data passed out and separate it.
Dim data = DirectCast(e.UserState, String())
'Update the UI.
table.Rows.Add(data)
End Sub
Note that you should NEVER touch the UI directly in the DoWork event handler or a method called from it. ONLY touch the UI on the UI thread. That means that the text in your TextBoxes must be extracted BEFORE calling RunWorkerAsync. You can eithewr pass the Strings in as arguments or you can assign them to fields and access them from there on any thread. Don't EVER access a member of a control on other than the UI thread. Some times it will work, sometimes it will appear to work but not do as intended and sometimes it will crash your app. So that you don't have to remember which specific scenarios cause which result, avoid such scenario altogether.
I haven't tested this code so I'm not sure but you may have to call Refresh on the grid or the form after adding the new row to the DataTable.
Variables
Well, let's start from the top with some class level variables:
'Notice the enabled properties.
Private WithEvents BackgroundWorker1 As New BackgroundWorker With {.WorkerReportsProgress = True, .WorkerSupportsCancellation = True}
'To monitor the cancellation, set by the Cancel Button.
Private bgwCancel As Boolean = False
'The DGV source.
Private dtResults As New DataTable
'The start directory.
Private startDir As String
'The search keyword.
Private searchWord As String
'Whether to search the sub directories, from a check box for example.
Private includeSubDirectories As Boolean = True
'Whether to search the files, from another check box.
Private includeFiles As Boolean = True
The Constructor
Prepare your DGV and whatever else you need here.
Sub New()
dtResults.Columns.Add(New DataColumn("Type", Type.GetType("System.String")))
dtResults.Columns.Add(New DataColumn("Search Result", Type.GetType("System.String")))
DataGridView1.DataSource = dtResults
DataGridView1.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
'Make sure you add the image column after binding the data source.
Dim imgCol As New DataGridViewImageColumn(False)
With imgCol
.Image = Nothing
.Name = "imgCol"
.HeaderText = ""
.Width = 50
.DefaultCellStyle.NullValue = Nothing
End With
DataGridView1.Columns.Insert(0, imgCol)
End Sub
Iterator
Now, let's write the search routine. I'd do that through an Iterator function:
Private Iterator Function IterateFolders(startDir As String, includeFiles As Boolean, includeSubDir As Boolean) As IEnumerable(Of String)
For Each dirName In IO.Directory.EnumerateDirectories(startDir)
Yield dirName
If includeFiles Then
For Each fileName In IO.Directory.EnumerateFiles(startDir)
Yield fileName
Next
End If
If includeSubDir Then
For Each subDir In IterateFolders(dirName, includeFiles, includeSubDir)
Yield subDir
Next
End If
Next
End Function
The Main Thread Updater
A routine called by the worker's thread to update the DataTable and any control that belongs to the main thread:
Private Sub AddSearchResult(path As String)
If InvokeRequired Then
Invoke(Sub() AddSearchResult(path))
Else
dtResults.Rows.Add(If(IO.File.Exists(path), "File", "Folder"), path)
sbStatusBar.Text = $"Searching {path}"
End If
End Sub
Start
In the click event of the start button, do the necessary validations, assign the values to their variables, and start the back ground worker:
If String.IsNullOrEmpty(txtSearchKeyword.Text) Then Return
If String.IsNullOrEmpty(txtSearchLocation.Text) Then Return
bgwCancel = False
dtResults.Rows.Clear()
startDir = txtSearchLocation.Text
searchWord = txtSearchKeyword.Text.ToLower
includeSubDirectories = chkIncludeSubDirs.Checked
includeFiles = chkFiles.Checked
btnSearch.Enabled = False
sbStatusBar.Text = "Searching..."
BackgroundWorker1.RunWorkerAsync()
Cancel
To cancel the search, in the click event of the cancel button I presume, True the bgwCancel variable:
bgwCancel = True
The BackgroundWorker - DoWork
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
For Each item As String In IterateFolders(startDir, includeFiles, includeSubDirectories)
If bgwCancel Then
BackgroundWorker1.CancelAsync()
Return
End If
If item.ToLower.Contains(searchWord) Then
AddSearchResult(item)
End If
Threading.Thread.Sleep(100)
Next
End Sub
Note that, Its good practice to give a lengthy routine a BREATH through the Sleep(ms) method of that thread.
The BackgroundWorker - ProgressChanged
I don't think you need it here.
The BackgroundWorker - RunWorkerCompleted
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
If bgwCancel Then
sbStatusBar.Text = "Canceled!"
MessageBox.Show("Canceled by you!")
ElseIf e.Error IsNot Nothing Then
sbStatusBar.Text = "Error!"
MessageBox.Show(e.Error.Message)
Else
sbStatusBar.Text = "Complete"
'YOU DO NOT NEED TO DO THIS. Remove the following
'DataGridView1.DataSource = Nothing
'DataGridView1.DataSource = dtResults
'DataGridView1.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
End If
btnSearch.Enabled = True
End Sub
The Image Column
Handle the RowsAdded event of the DGV as follow:
Private Sub DataGridView1_RowsAdded(sender As Object, e As DataGridViewRowsAddedEventArgs) Handles DataGridView1.RowsAdded
If DataGridView1.Columns.Count < 3 Then Return
'if you want to get rid of the default x image.
If e.RowIndex = 0 Then
DataGridView1.Rows(e.RowIndex).Cells("imgCol").Value = Nothing
End If
Dim path As String = DataGridView1.Rows(e.RowIndex).Cells(2).Value?.ToString
If Not String.IsNullOrEmpty(path) Then
If IO.File.Exists(path) Then
DataGridView1.Rows(e.RowIndex).Cells("imgCol").Value = Icon.ExtractAssociatedIcon(path).ToBitmap
Else
DataGridView1.Rows(e.RowIndex).Cells("imgCol").Value = My.Resources.Folder
End If
End If
End Sub
Where the My.Resources.Folder is an icon file of your choice for the folder entries.
Good luck.

function that runs when dynamically generated control is interacted with

I've been Having trouble with making a sub that runs when my datagridview cell is doubleclicked. It is caused because the datagridview is programmatically created, rather than created by the designer. I have found a help website i will include that appears to be related to the issue.
Public Class seattemplatecreator
Dim alphabet() As Char = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
Private WithEvents dgv_flightTemplate As DataGridView
'help from https://it.toolbox.com/question/event-for-dynamically-created-command-button-043008
Public Sub init(ByVal dgv01 As DataGridView)
dgv_flightTemplate = dgv01
End Sub
Private Sub dgv_flightTemplate_CellMouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgv_flightTemplate.CellMouseDoubleClick
MsgBox("workwd")
End Sub
Private Sub btn_createflight_Click(sender As Object, e As EventArgs) Handles btn_createflight.Click
'used https://social.msdn.microsoft.com/Forums/vstudio/en-US/e222f438-f060-4e61-ab28-523d02db91b2/how-to-programmatically-create-datagridview-with-empty-columns-and-rows?forum=vbgeneral
'to help with this part for automatically generating the datagridview
MsgBox(alphabet(0))
Dim dgv_flightTemplate As New DataGridView
Dim c As Integer = txb_columns.Text
Dim r As Integer = txb_rows.Text
For colcount As Integer = 0 To c - 1
Dim nc As New DataGridViewTextBoxColumn
nc.Name = "Seating Column"
dgv_flightTemplate.Columns.Add(nc)
Next
dgv_flightTemplate.Rows.Add(r)
For x = 0 To r - 1
dgv_flightTemplate.Rows(x).HeaderCell.Value = alphabet(x).ToString
Next
Me.Controls.Add(dgv_flightTemplate)
dgv_flightTemplate.Location = New Point(400, 400)
dgv_flightTemplate.AllowUserToAddRows = False
dgv_flightTemplate.AllowUserToDeleteRows = False
dgv_flightTemplate.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders
dgv_flightTemplate.AutoResizeRows()
dgv_flightTemplate.AutoSize = True
End Sub
End Class
https://it.toolbox.com/question/event-for-dynamically-created-command-button-043008
Edit: Olivier Jacot-Descombes response was perfect all that was needed was run the "Init" sub.
Public Class seattemplatecreator
Dim alphabet() As Char = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray()
Private WithEvents dgv_flightTemplate As DataGridView
'help from https://it.toolbox.com/question/event-for-dynamically-created-command-button-043008
Public Sub init(ByVal dgv01 As DataGridView)
dgv_flightTemplate = dgv01
End Sub
Private Sub dgv_flightTemplate_CellMouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles dgv_flightTemplate.CellMouseDoubleClick
MsgBox("workwd")
End Sub
Private Sub btn_createflight_Click(sender As Object, e As EventArgs) Handles btn_createflight.Click
'used https://social.msdn.microsoft.com/Forums/vstudio/en-US/e222f438-f060-4e61-ab28-523d02db91b2/how-to-programmatically-create-datagridview-with-empty-columns-and-rows?forum=vbgeneral
'to help with this part for automatically generating the datagridview
MsgBox(alphabet(0))
Dim dgv_flightTemplate As New DataGridView
Dim c As Integer = txb_columns.Text
Dim r As Integer = txb_rows.Text
For colcount As Integer = 0 To c - 1
Dim nc As New DataGridViewTextBoxColumn
nc.Name = "Seating Column"
dgv_flightTemplate.Columns.Add(nc)
Next
dgv_flightTemplate.Rows.Add(r)
For x = 0 To r - 1
dgv_flightTemplate.Rows(x).HeaderCell.Value = alphabet(x).ToString
Next
Me.Controls.Add(dgv_flightTemplate)
dgv_flightTemplate.Location = New Point(400, 400)
dgv_flightTemplate.AllowUserToAddRows = False
dgv_flightTemplate.AllowUserToDeleteRows = False
dgv_flightTemplate.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders
dgv_flightTemplate.AutoResizeRows()
dgv_flightTemplate.AutoSize = True
init(dgv_flightTemplate)
End Sub
End Class
Any help would be greatly appreciated
Thanks, Taine
You are not calling Init. But instead, you could as well directly assign to the field
dgv_flightTemplate = New DataGridView 'Note: No Dim here.
But even if you are creating the columns dynamically, you could add a grid with the designer. Just call
dgv_flightTemplate.Columns.Clear()
before adding columns.

looping through datagridview

Mine is a windows app. containing forms named BOM nd BOMSelected..
There is datagridview in BOM which contains checkbox column.. When the user selects checkbox, the selected rows should be seen in the datagridview of other form, SelectedBom..
I have coded but don't get it working.. Some error..
Can you please help ??
Your Help is greatly appreciated..
Here is what i have done !!
Public Class SelectedBom
Private Sub SelectedBom_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'HemDatabase1DataSet4.partno' table. You can move, or remove it, as needed.
'Me.PartnoTableAdapter.Fill(Me.HemDatabase1DataSet4.partno)
Dim count As Integer = 0
For j As Integer = 0 To BOM.dgv1.RowCount - 1
If BOM.dgv1.Rows(j).Cells(0).Value = True Then
Dim ro As New DataGridViewRow
DataGridView2.Rows.Add(ro)
For i As Integer = 0 To BOM.dgv1.ColumnCount - 1
Me.DataGridView2.Rows(count).Cells(i).Value = BOM.dgv1.Rows(j).Cells(i).Value
Next
count += 1
End If
Next
End Sub
End Class
Try,
For Each row As DataGridViewRow In BOM.dgv1.Rows
Dim obj(row.Cells.Count - 1) As Object
For i = 0 To row.Cells.Count - 1
obj(i) = row.Cells(i).Value
Next
Me.DataGridView2.Rows.Add(obj)
Next
EDIT:
Demo:
Add Button1 and DataGridView1 in BOM form
Public Class BOM
Public Class Sample
Public Property Satus As Boolean
Public Property Name As String
Public Property ID As Integer
End Class
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
SelectedBom.Show()
End Sub
Private Sub BOM_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim myList As New List(Of Sample)
myList.Add(New Sample() With {.ID = 1, .Name = "A"})
myList.Add(New Sample() With {.ID = 2, .Name = "B"})
myList.Add(New Sample() With {.ID = 3, .Name = "C"})
DataGridView1.DataSource = myList
End Sub
End Class
Add DataGridView1 in SelectBOM form
Public Class SelectedBom
Private Sub SelectedBom_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim i As Integer = 0
DataGridView1.AutoGenerateColumns = False
DataGridView1.Columns.Add("Name", "Name")
DataGridView1.Columns.Add("No", "No")
For Each row As DataGridViewRow In BOM.DataGridView1.Rows
If DirectCast(row.Cells(0).Value, Boolean) Then
DataGridView1.Rows.Add(row.Cells(1).Value, row.Cells(2).Value)
End If
Next
End Sub
End Class
Maybe instead of using the for each statement, you should instead use:
for istep as integer = 0 to datagridview.rowcount - 2
With the for each syntax, you can't assign a value to the individual row as you walk down the row.