我创建了两个表父和子。
Cus:父母
+----+-------------------------+------+
| ID | Name | Age |
+----+-------------------------+------+
| 1 | Japhet | 22 |
| 2 | Abegail | 31 |
| 3 | Norlee | 35 |
| 4 | Pacita | 60 |
| 5 | Reynaldo | 65 |
| 6 | Barro, Reynaldo Batucan | 65 |
| 7 | Batucan, Japhet C. | NULL |
| 8 | Barro, Reynaldo B. | NULL |
+----+-------------------------+------+
Cus2:孩子
+-----+----+------+---------+
| QID | ID | Name | Country |
+-----+----+------+---------+
| | | | |
+-----+----+------+---------+
我使用下面的代码用自定义行填充datagridview,但是当我尝试保存它时,它不会保存。我收到此错误消息:
输入字符串的格式不正确。无法存储在ID列中。预期的类型是Int32。
此外,Cus.ID不会填入Cus2.ID
Private Sub Populate()
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn(3) {New DataColumn("QID", GetType(Integer)), New DataColumn("ID", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Country", GetType(String))})
Try
dt.Rows.Add(1, 0, "John Hammond", "United States")
dt.Rows.Add(2, 0, "Mudassar Khan", "India")
dt.Rows.Add(3, 0, "Suzanne Mathews", "France")
dt.Rows.Add(4, 0, "Robert Schidner", "Russia")
Me.Cus2DataGridView.DataSource = dt
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Populate()
End Sub
Private Sub Cus2DataGridView_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles Cus2DataGridView.CellContentClick
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each row As DataGridViewRow In Cus2DataGridView.Rows
Dim constring As String = "Data Source=DESKTOP-0M1930H\PNJK;Initial Catalog=Hello;Integrated Security=True"
Using con As New SqlConnection(constring)
Using cmd As New SqlCommand("INSERT INTO Cus2 VALUES(@QID, @ID, @Name, @Country)", con)
Try
cmd.Parameters.AddWithValue("@QID", row.Cells("QID").Value)
cmd.Parameters.AddWithValue("@ID", row.Cells("ID").Value)
cmd.Parameters.AddWithValue("@Name", row.Cells("Name").Value)
cmd.Parameters.AddWithValue("@Country", row.Cells("Country").Value)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
Catch ex As Exception
End Try
End Using
End Using
Next
End Sub
我是新手,所以请帮忙。谢谢:D