looping through datagridview - vb.net

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.

Related

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

Vb.net bindingsource.filter from a list of strings

i have in a windows.form a combobox and a datagridview,
i add rows in datagridview with a button and get the value(string) from combobox and if i double click on the row of datagridview i delete the row.
When i add the row i want to hide/disable/remove the combobox value and when i delete the row i want to restore it in combobox.
The combobox values are binding from dataset source and combobox is dropdownlist style.
I try some things until now but this is what i think is better approach and where i am:
Dim filterList As List(Of String) = New List(Of String)
Private Sub filterListAdd()
Dim dgResult As String
filterList .Clear() 'Clear the list so no duplicates
For i As Integer = 0 To combobox.Items.Count - 1
Dim a As String = combobox.GetItemText(combobox.Items(i))
For row As Integer = 0 To Dgview.RowCount - 1
For col As Integer = 0 To Dgview.ColumnCount - 1
Next
Surname = Dgview.Rows(row).Cells(0).Value.ToString
If dgResult = a Then
filterList .Add(a) 'Add to list
End If
Next
Next i
End Sub
Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button.Click
Dgview.Rows.Add(combobox.Text)
filterListAdd()
'Here i want to bindingsource.filter = filterList
End Sub
Private Sub Dgview_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles Dgview.MouseDoubleClick
Dgview.Rows.Remove(Dgview.CurrentRow)
'I Guess here with the same way i filter it again
End Sub
Any help will be appreciated, thanks in advance.
Panos
Public Class Form1
Dim clsItems As New ArrayList()
Private Sub RemoveComboItem()
Me.BindingSource.Position = Me.BindingSource.Find("1", Combobox.Text)
Dim 1Add As String = DirectCast(BindingSource.Current, DataRowView).Item("1").ToString
Dim 2Add As String = DirectCast(BindingSource.Current, DataRowView).Item("2").ToString
Dim 3Add As String = DirectCast(BindingSource.Current, DataRowView).Item("3").ToString
clsItems.Add(New MyItem(1Add, 2Add, 3Add))
BindingSource.RemoveCurrent()
End Sub
Private Sub AddComboItem(dg As DataGridView) ' Because i have two datagridviews
Dim 1 As String = dg.CurrentRow.Cells(0).Value.ToString()
For i = 0 To clsItems.Count - 1
If i <= clsItems.Count - 1 Then
If 1 = clsItems(i).1 Then
Dim drNewRow As DataRow
drNewRow = DeeDataSet.Tables("Table").NewRow()
drNewRow("1") = clsItems(i).1
drNewRow("2") = clsItems(i).2
drNewRow("3") = clsItems(i).3
DeeDataSet.Tables("Table").Rows.Add(drNewRow)
clsItems.Remove(clsItems(i)) ' Remove it from array so no duplicates
End If
End If
Next
End Sub
Private Sub Button_Click(sender As Object, e As EventArgs) Handles Button.Click
RemoveComboItem()
End Sub
Private Sub Dgview_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles Dgview.MouseDoubleClick
AddComboItem(Dgview)
Dgview.Rows.Remove(Dgview.CurrentRow)
End Sub
End class
Public Class MyItem
Private m_s1 As String
Private m_s2 As String
Private m_s3 As String
Public Sub New(1As String, 2 As String, 3 As String)
M_sName = 1
M_sSurname = 2
M_sTitle = 3
End Sub
Public ReadOnly Property 1
Get
Return m_s1
End Get
End Property
Public ReadOnly Property 2
Get
Return M_s2
End Get
End Property
Public ReadOnly Property 3
Get
Return M_s3
End Get
End Property
End Class
In that form i don't update the dataset because every change i want to make it in other form, so when i finish from here the dataset.table has no changes.

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.

Control Event (Changed) In DataTable

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

Visual basic 2010, database – how to fill specific field

I'm creating database connection in Visual Basic. When user click on "borrow book" it transfer chosen data into table used for lent books. It all works alright, but I need last thing. In my database in lent table I have attribute "End date of lent" and I want fill it everytime when user borrow a book with date today + 1 month (for instance, if now is 19/04/2016, end date will be 19/05/2016). I created method "BorrowTime" for this, but I don't know what I should type into and how can I get value of inserted row into "row". And sorry for horrible look of code and form...
Public Class frm_UserView
Dim BooksSource As New BindingSource
Dim BorrowSource As New BindingSource
Dim BooksView As New DataView
Dim BorrowView As New DataView
Dim ds As New DataSet
Dim Borrow As Byte
Private Sub frm_UserView_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
tmr_Timer.Start()
Me.LoanerBooksTableAdapter.Fill(Me.GMITLibraryDataSet1.LoanerBooks)
Me.BooksTableAdapter.Fill(Me.GMITLibraryDataSet.Books)
BooksSource = dgd_UserBookView.DataSource
BooksView = CType(BooksSource.List, DataView)
ds = BooksView.DataViewManager.DataSet.Clone
BorrowSource.DataSource = ds
BorrowSource.DataMember = "Books"
BorrowView = CType(BorrowSource.List, DataView)
dgd_User_Borrow_View.DataSource = BorrowSource
End Sub
Private Sub btn_Borrow_Click(sender As System.Object, e As System.EventArgs) Handles btn_BorrowBook.Click
Borrow = 1
MoveBooks(dgd_UserBookView, BorrowView, Borrow)
dgd_User_Borrow_View.Sort(dgd_User_Borrow_View.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
BorrowSource.MoveLast()
BorrowSource.MoveLast()
End Sub
Private Sub MoveBooks(ByRef source As DataGridView, ByRef target As DataView, ByRef borrow As Byte)
For i = 0 To source.SelectedRows.Count - 1
Dim numberOfRow As Integer
Dim row As DataRowView
row = target.AddNew()
Dim col As Int16 = 0
For Each cell As DataGridViewCell In source.SelectedRows(i).Cells
row.Item(col) = cell.Value
If borrow = 1 Then
numberOfRow = 0
BorrowTime(numberOfRow, dgd_User_Borrow_View)
End If
col = col + 1
Next
Next
Dim count As Int16 = source.SelectedRows.Count
For i = 0 To count - 1
source.Rows.RemoveAt(source.SelectedRows(0).Index)
Next
End Sub
Private Sub BorrowTime(ByRef row As Integer, ByRef dgd_Table As DataGridView)
'Code for adding date
End Sub
Private Sub btn_ReturnBook_Click(sender As System.Object, e As System.EventArgs) Handles btn_ReturnBook.Click
Borrow = 0
MoveBooks(dgd_User_Borrow_View, BooksView, Borrow)
dgd_UserBookView.Sort(dgd_UserBookView.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
BooksSource.MoveLast()
BooksSource.MoveLast()
End Sub
Private Sub btn_UserLogOut_Click(sender As System.Object, e As System.EventArgs) Handles btn_UserLogOut.Click
frm_Login.Show()
Me.Hide()
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles tmr_Timer.Tick
Dim countBooks As Integer
Dim countLent As Integer
countBooks = BooksSource.Count
countLent = BorrowSource.Count
lbl_BookCounter.Text = "There are " + countBooks.ToString + " books"
lbl_BorrowCounter.Text = "You have lent " + countLent.ToString + " books"
End Sub
End Class
I need to put code here:
Private Sub BorrowTime(ByRef row As Integer, ByRef dgd_Table As DataGridView)
'Code for adding date
End Sub
My form
Public Class frm_UserView
Dim BooksSource As New BindingSource
Dim BorrowSource As New BindingSource
Dim BooksView As New DataView
Dim BorrowView As New DataView
Dim ds As New DataSet
Dim Borrow As Byte
Private Sub frm_UserView_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
tmr_Timer.Start()
Me.LoanerBooksTableAdapter.Fill(Me.GMITLibraryDataSet1.LoanerBooks)
Me.BooksTableAdapter.Fill(Me.GMITLibraryDataSet.Books)
BooksSource = dgd_UserBookView.DataSource
BooksView = CType(BooksSource.List, DataView)
ds = BooksView.DataViewManager.DataSet.Clone
BorrowSource.DataSource = ds
BorrowSource.DataMember = "Books"
BorrowView = CType(BorrowSource.List, DataView)
dgd_User_Borrow_View.DataSource = BorrowSource
End Sub
Private Sub btn_Borrow_Click(sender As System.Object, e As System.EventArgs) Handles btn_BorrowBook.Click
Borrow = 1
MoveBooks(dgd_UserBookView, BorrowView, Borrow)
dgd_User_Borrow_View.Sort(dgd_User_Borrow_View.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
BorrowSource.MoveLast()
BorrowSource.MoveLast()
End Sub
Private Sub MoveBooks(ByRef source As DataGridView, ByRef target As DataView, ByRef borrow As Byte)
For i = 0 To source.SelectedRows.Count - 1
Dim numberOfRow As Integer
Dim row As DataRowView
row = target.AddNew()
Dim col As Int16 = 0
For Each cell As DataGridViewCell In source.SelectedRows(i).Cells
row.Item(col) = cell.Value
If borrow = 1 Then
numberOfRow = 0
BorrowTime(numberOfRow, dgd_User_Borrow_View)
End If
col = col + 1
Next
Next
Dim count As Int16 = source.SelectedRows.Count
For i = 0 To count - 1
source.Rows.RemoveAt(source.SelectedRows(0).Index)
Next
End Sub
Private Sub BorrowTime(ByRef row As Integer, ByRef dgd_Table As DataGridView)
'Code for adding date
End Sub
Private Sub btn_ReturnBook_Click(sender As System.Object, e As System.EventArgs) Handles btn_ReturnBook.Click
Borrow = 0
MoveBooks(dgd_User_Borrow_View, BooksView, Borrow)
dgd_UserBookView.Sort(dgd_UserBookView.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
BooksSource.MoveLast()
BooksSource.MoveLast()
End Sub
Private Sub btn_UserLogOut_Click(sender As System.Object, e As System.EventArgs) Handles btn_UserLogOut.Click
frm_Login.Show()
Me.Hide()
End Sub
Private Sub Timer1_Tick(sender As System.Object, e As System.EventArgs) Handles tmr_Timer.Tick
Dim countBooks As Integer
Dim countLent As Integer
countBooks = BooksSource.Count
countLent = BorrowSource.Count
lbl_BookCounter.Text = "There are " + countBooks.ToString + " books"
lbl_BorrowCounter.Text = "You have lent " + countLent.ToString + " books"
End Sub
End Class