The record cannot be deleted or changed because table 'Modules' includes related records - vb.net

Having a problem with deleting records this exception keeps occurring.
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll
Additional information: The record cannot be deleted or changed because table 'Modules' includes related records.
Public Class frmStudentDatabase
Dim objConnection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=StudentDatabase.accdb")
Dim objStudentDA As New OleDb.OleDbDataAdapter("Select * From Students", objConnection)
Dim objStudentCB As New OleDb.OleDbCommandBuilder(objStudentDA)
Dim objDataSet As New DataSet()
Dim objModuleDA As New OleDb.OleDbDataAdapter("Select * From Modules", objConnection)
Dim objModuleCB As New OleDb.OleDbCommandBuilder(objModuleDA)
Private Sub frmStudentDatabase_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Call the sub procedure that will fill the dataset
'Create (Relationships) and Retrieve all Student_ID numbers
Retrieve()
End Sub
Private Sub cboStudents_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboStudents.SelectedIndexChanged
FillStudentDetails()
FillModuleDetails()
End Sub
Public Sub Retrieve()
objDataSet.Clear()
objStudentDA.FillSchema(objDataSet, SchemaType.Source, "Students")
objStudentDA.Fill(objDataSet, "Students")
objModuleDA.FillSchema(objDataSet, SchemaType.Source, "Modules")
objModuleDA.Fill(objDataSet, "Modules")
objDataSet.Relations.Clear()
objDataSet.Relations.Add("Students2Modules", objDataSet.Tables("Students").Columns("Student_ID"), _
objDataSet.Tables("Modules").Columns("Student_ID"))
'Empty combo box
cboStudents.Items.Clear()
'Loop through each row, adding the Student_ID to the combobox
Dim i As Integer, strCurrentID As String
For i = 1 To objDataSet.Tables("Students").Rows.Count
strCurrentID = objDataSet.Tables("Students").Rows(i - 1).Item("Student_ID")
cboStudents.Items.Add(strCurrentID)
Next
'Select first item in the list
cboStudents.SelectedIndex = 0
FillStudentDetails()
FillModuleDetails()
End Sub
Public Sub FillStudentDetails()
Dim objRow As DataRow
objRow = objDataSet.Tables("Students").Rows.Find(cboStudents.SelectedItem)
txtStudentID.Text = objRow.Item("Student_ID")
txtStudentName.Text = objRow.Item("Student_Name")
txtStudentAddress.Text = objRow.Item("Student_Address")
End Sub
Public Sub FillModuleDetails()
Dim objStudent As DataRow, objModule As DataRow
Dim strModuleEntry As String
'Clear any existing modules
lstModules.Items.Clear()
'Find the current student record
objStudent = objDataSet.Tables("Students").Rows.Find(cboStudents.SelectedItem.ToString)
For Each objModule In objStudent.GetChildRows("Students2Modules")
strModuleEntry = objModule.Item("Module_ID") & "," & objModule.Item("Module_Name") &
"," & objModule.Item("Module_Desc")
lstModules.Items.Add(strModuleEntry)
DataGridView1.DataSource = objDataSet.Tables("Modules")
Next
End Sub
Private Sub btnNew_Click(sender As Object, e As EventArgs) Handles btnNew.Click
Dim objRow As DataRow
Dim objRowModules As DataRow
Dim RowIndex As Integer
objRow = objDataSet.Tables("Students").NewRow
objRow.Item("Student_Name") = InputBox("Please Enter Student Name:")
objRow.Item("Student_Address") = InputBox("Please Enter Student Address:")
'Add data row to table
objDataSet.Tables("Students").Rows.Add(objRow)
objStudentDA.Update(objDataSet, "Students")
'Set up the module data row object
objRowModules = objDataSet.Tables("Modules").NewRow
'Find the number of the last row
RowIndex = objDataSet.Tables("Students").Rows.Count - 1
'Tell vb.net to get the Student_ID value from the last row
objRowModules.Item("Student_ID") = objDataSet.Tables("Students").Rows(RowIndex)("Student_ID")
objRowModules.Item("Module_Name") = InputBox("Please Enter Module Name:")
objRowModules.Item("Module_Desc") = InputBox("Please Enter Module Description:")
'Add to the DB
objDataSet.Tables("Modules").Rows.Add(objRowModules)
'Update the data adapter
objModuleDA.Update(objDataSet, "Modules")
MessageBox.Show("New record saved", "Saved")
Retrieve()
End Sub
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
'Code to modify an existing record
Dim objRowCurrent As DataRow
objRowCurrent = objDataSet.Tables("Students").Rows.Find(cboStudents.SelectedItem.ToString)
'We cannot modify the ID as it is an AutoNumber
objRowCurrent("Student_Name") = txtStudentName.Text
objRowCurrent("Student_Address") = txtStudentAddress.Text
objStudentDA.Update(objDataSet, "Students")
objDataSet.AcceptChanges()
'Now that we made changes, we need to retrieve the new data
Retrieve()
End Sub
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
'Dim i As integer, strCurrentID As String
Dim StudentName As String
Dim StudentFound As Boolean = False
StudentName = InputBox("Enter a Name Please!", "Search")
For i As Integer = 0 To (objDataSet.Tables("Students").Rows.Count - 1)
If CStr(objDataSet.Tables("Students").Rows(i)("Student_Name")) = StudentName Then
StudentFound = True
cboStudents.SelectedIndex = i
FillStudentDetails()
FillModuleDetails()
End If
Next
End Sub
Private Sub btnNext_Click(sender As Object, e As EventArgs) Handles btnNext.Click
Dim rowIndex As Integer = cboStudents.SelectedItem - 1
If (rowIndex < objDataSet.Tables("Students").Rows.Count - 1) Then
rowIndex = rowIndex + 1
cboStudents.SelectedIndex = rowIndex
FillStudentDetails()
FillModuleDetails()
Else
MessageBox.Show("No more records to display", "End")
End If
End Sub
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
Dim objRow As DataRow
objRow = objDataSet.Tables("Students").Rows.Find(txtStudentID.Text)
'Remember that all related child rows will be deleted! So no need to
'set up a new datarow for the Pet table
objRow.Delete()
objStudentDA.Update(objDataSet, "Students")
Retrieve()
End Sub
Private Sub btnPrevious_Click(sender As Object, e As EventArgs) Handles btnPrevious.Click
Dim rowIndex As Integer = cboStudents.SelectedItem - 1
If (rowIndex > 0) Then
rowIndex = rowIndex - 1
cboStudents.SelectedIndex = rowIndex
FillStudentDetails()
FillModuleDetails()
Else
MessageBox.Show("No more records to display", "Start")
End If
End Sub
End Class

You try to remove a record which has child records. Due to those references your removal fails. The reason is that the Student has Modules. You will need to remove the references to the Student before you can remove it.

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

Datagridview Horizontal to vertical button

The following code isn't working when exporting the datagridview data when trying to make it vertical with headers along the left side along with text beside each one. Once this is flipped the user would click on button1 to export to excel.
Imports System.Data.DataTable
Imports System.IO
Imports Microsoft.Office.Interop
Public Class Form1
Dim table As New DataTable(0)
Public checkBoxList As List(Of CheckBox)
Private ds As DataSet = Nothing
Private dt As DataTable = Nothing
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
ds = New DataSet()
dt = New DataTable()
ds.Tables.Add("Table")
Dim my_DataView As DataView = ds.Tables(0).DefaultView
DataGridView1.DataSource = my_DataView
table.Columns.Add("Forename", Type.GetType("System.String"))
table.Columns.Add("Surname", Type.GetType("System.String"))
table.Columns.Add("Food", Type.GetType("System.String"))
checkBoxList = New List(Of CheckBox) From {CheckBox1, CheckBox2, CheckBox3, CheckBox4}
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim currentDataSet As DataSet = FlipDataSet(ds) ' Flip the DataSet
Dim values As String = "" &
String.Join(" & ", checkBoxList _
.Where(Function(cb) cb.Checked).Select(Function(cb) cb.Text))
' use values for placing into your DataGridView
CheckBox1.Text = values
CheckBox2.Text = values
CheckBox3.Text = values
CheckBox4.Text = values
table.Rows.Add(TextBox1.Text, TextBox2.Text, values.ToString)
DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill
DataGridView1.RowTemplate.Height = 100
DataGridView1.AllowUserToAddRows = False
DataGridView1.DataSource = table
'Save to excel with headers
Dim ExcelApp As Object, ExcelBook As Object
Dim ExcelSheet As Object
Dim i As Integer
Dim j As Integer
'create object of excel
ExcelApp = CreateObject("Excel.Application")
ExcelBook = ExcelApp.WorkBooks.Add
ExcelSheet = ExcelBook.WorkSheets(1)
With ExcelSheet
For Each column As DataGridViewColumn In DataGridView1.Columns
.cells(1, column.Index + 1) = column.HeaderText
Next
For i = 1 To Me.DataGridView1.RowCount
.cells(i + 1, 1) = Me.DataGridView1.Rows(i - 1).Cells("Forename").Value
For j = 1 To DataGridView1.Columns.Count - 1
.cells(i + 1, j + 1) = DataGridView1.Rows(i - 1).Cells(j).Value
Next
Next
End With
ExcelApp.Visible = True
'
ExcelSheet = Nothing
ExcelBook = Nothing
ExcelApp = Nothing
End Sub
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
Public Function FlipDataSet(ByVal my_DataSet As DataSet) As DataSet
Dim ds As New DataSet()
For Each dt As DataTable In my_DataSet.Tables
Dim table As New DataTable()
For i As Integer = 0 To dt.Rows.Count
table.Columns.Add(Convert.ToString(i))
Next
Dim r As DataRow
For k As Integer = 0 To dt.Columns.Count - 1
r = table.NewRow()
r(0) = dt.Columns(k).ToString()
For j As Integer = 1 To dt.Rows.Count
r(j) = dt.Rows(j - 1)(k)
Next
table.Rows.Add(r)
Next
ds.Tables.Add(table)
Next
Return ds
End Function
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim currentDataSet As DataSet = FlipDataSet(ds) ' Flip the DataSet
Dim currentDataView As DataView = currentDataSet.Tables(0).DefaultView
DataGridView1.DataSource = currentDataView
Button2.Enabled = False
End Sub
End Class
When clicking button2 it should flip the data with the following;
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles
Button2.Click
Dim currentDataSet As DataSet = FlipDataSet(ds) ' Flip the DataSet
Dim currentDataView As DataView = currentDataSet.Tables(0).DefaultView
DataGridView1.DataSource = currentDataView
Button2.Enabled = False
End Sub
End Class
I've tried debugging but it i can't seem to find anything wrong? It will allow me to insert data in the textbox's whilst selecting checkbox's and when clicking button 1 to export it works fine, but it doesn't flip the data.
Please can anyone suggest how to fix this as i have a presentation on the 8th June and this data needs to automatically be flipped
Sourcecode: Download Myproject
Image of target
Answered:
Imports Microsoft.Office.Interop
Imports System.Runtime.InteropServices
Public Class Form1
Private ds As DataSet = Nothing
Private dt As DataTable = Nothing
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.AllowUserToAddRows = False
dt = New DataTable("MyTable")
dt.Columns.Add("Forename", Type.GetType("System.String"))
dt.Columns.Add("Surname", Type.GetType("System.String"))
dt.Columns.Add("Food", Type.GetType("System.String"))
ds = New DataSet
ds.Tables.Add(dt)
Dim my_DataView As DataView = ds.Tables("MyTable").DefaultView
DataGridView1.DataSource = my_DataView
End Sub
Private Sub Button_AddRowData_Click(sender As Object, e As EventArgs) Handles Button_AddRowData.Click
Dim foods As String = String.Join(" & ", CheckedListBox1.CheckedItems.Cast(Of String))
dt.Rows.Add(New Object() {TextBox_Forename.Text, TextBox_Surname.Text, foods})
End Sub
Private Sub Button_FlipAndSave_Click(sender As Object, e As EventArgs) Handles Button_FlipAndSave.Click
FlipAndSave(ds.Tables("MyTable"))
End Sub
Private Sub FlipAndSave(table As DataTable)
Dim ExcelApp As New Excel.Application
Dim WrkBk As Excel.Workbook = ExcelApp.Workbooks.Add()
Dim WrkSht As Excel.Worksheet = CType(WrkBk.Worksheets(1), Excel.Worksheet)
With WrkSht
For ci As Integer = 0 To table.Columns.Count - 1
.Cells(ci + 1, 1) = table.Columns(ci).ColumnName
Next
For ri As Integer = 0 To table.Rows.Count - 1
For ci As Integer = 0 To table.Columns.Count - 1
.Cells(ci + 1, ri + 2) = table.Rows(ri).Item(ci).ToString
Next
Next
End With
ExcelApp.Visible = True
'use this lines if you want to automatically save the WorkBook
'WrkBk.SaveAs("C:\Some Folder\My Workbook.xlsx") '(.xls) if you have an old version of Excel
'ExcelApp.Quit() 'use this line if you want to close the Excel Application
ReleaseObject(ExcelApp)
ReleaseObject(WrkBk)
ReleaseObject(WrkSht)
End Sub
Private Sub ReleaseObject(obj As Object)
Marshal.ReleaseComObject(obj)
obj = Nothing
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

How to remove data row from data table base on column name with primary key

I would like to remove data row from datantable in vb.net.
When I find the row based on column with primary key, it return error . I google but cannot resolve the error .
This is my code
Private Sub frmMatching_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dtFromCustomer = New DataTable()
dtToCusotmer = New DataTable()
dtTemp = New DataTable()
SetColumn()
BindFromCustomer()
BindToCustomer()
End Sub
Private Sub SetColumn()
Dim keyColumn As New DataColumn()
keyColumn.ColumnName = "CV_CODE"
keys(0) = keyColumn
dtFromCustomer.Columns.Add(keyColumn)
dtFromCustomer.Columns.Add("CV_NAME")
dtFromCustomer.PrimaryKey = keys
End Sub
Private Sub BindFromCustomer()
Dim ds As New DataSet
ds.Clear()
ds = GetDataset(sql)
Try
If ds.Tables(0).Rows.Count > 0 Then
dtFromCustomer = ds.Tables(0)
dtFromCustomer.PrimaryKey = Nothing
Dim col As DataColumn = dtFromCustomer.Columns("CV_CODE")
dtFromCustomer.AcceptChanges()
gvFromCustomer.DataSource = dtFromCustomer
End If
End Sub
Private Sub btnAddOne_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddOne.Click
If gvFromCustomer.SelectedRows.Count > 0 And dtFromCustomer.Rows.Count > 0 Then
Dim dr As DataRow
Dim i As Integer = 0
Try
Dim foundRow As DataRow
Dim findThese(0) As Object
findThese(0) = gvFromCustomer.SelectedRows(0).Cells("CV_CODE").Value.ToString()
foundRow = dtFromCustomer.Rows.Find(findThese)
If Not (foundRow Is Nothing) Then 'row is found
dtFromCustomer.Rows.Remove(foundRow)
Exit Sub
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
dtFromCustomer.AcceptChanges()
gvFromCustomer.DataSource = dtFromCustomer
gvToCustomer.Refresh()
End If
My error get this line
foundRow = dtFromCustomer.Rows.Find(findThese)

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.