gpt4 book ai didi

mysql - 如何将Datagridview中当前选定的行插入到数据库

转载 作者:行者123 更新时间:2023-11-29 21:31:59 25 4
gpt4 key购买 nike

     For i As Integer = Me.DataGridView1.SelectedRows.Count - 1 To 0 Step -1
Dim SDA1 As New MySqlDataAdapter
Dim bSource1 As New BindingSource
Dim dbDataSet1 As New DataTable
qty = DataGridView1.Rows(i).Cells(0).Value
auth = DataGridView1.Rows(i).Cells(1).Value()
title = DataGridView1.Rows(i).Cells(2).Value()
callnumber = DataGridView1.Rows(i).Cells(3).Value()
shelf = DataGridView1.Rows(i).Cells(4).Value()
Dim Query As String
Query = "Insert into returnedlist(quantity,author,title ,call_number,shelf,student_id,due_date,date_added) values('" & qty & "','" & auth & "','" & title & "','" & callnumber & "','" & shelf & "','" & TextBox2.Text.ToString & "','" & DateTimePicker1.Text & "', Now())"
COMMAND = New MySqlCommand(Query, MysqlConn)
SDA1.SelectCommand = COMMAND
SDA1.Fill(dbDataSet1)
bSource1.DataSource = dbDataSet1
Me.DataGridView1.DataSource = bSource1
SDA1.Update(dbDataSet1)
Next


**Code for Select**
ElseIf ComboBox2.Text = "Author" Then
Dim Query As String
Query = "Select id as 'ID', quantity as 'Qty',author as 'Author',title as 'Title',call_number as 'Call Number',location as 'Shelf #' from librarydb.blist where author like'%" & TextBox1.Text & "%' ORDER by author"
COMMAND = New MySqlCommand(Query, MysqlConn)
SDA.SelectCommand = COMMAND
If SDA.Fill(dbDataSet) Then
bSource.DataSource = dbDataSet
DataGridView1.DataSource = bSource
TextBox1.Text = ""
ComboBox2.Text = ""

Else
TextBox1.Text = ""
ComboBox2.Text = ""
MessageBox.Show("No Results found", "Informed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If

我想要做的是我想在数据库中插入我在 Datagridview 中选择的行。

代码可以工作,但问题是:即使我选择选择row3,它总是会插入到datagridview中的db row1。

这与我的 Datagridview 的属性有关吗?

最佳答案

MySqlDataAdapterUpdate 方法能够更新作为输入传递的具有 RowState 属性的 DataTable 中存在的所有行与值Unchanged不同。

当您编辑绑定(bind)到 DataTable 的 DataGridView 时,在网格上所做的更改会立即反射(reflect)在基础 DataTable 中,并且编辑的行将具有其 RowState property根据所做的编辑进行相应更改。

要完成这项工作,您需要做一些事情。

首先全局声明用于检索数据表的MySqlDataAdapter

Dim SDA1 As MySqlDataAdapter

然后在加载数据表的代码中确保还包含作为主键的列

' Here ID is assumed to be your primarykey'
SDA1 = New MySqlDataAdapter("SELECT ID, ...... FROM returnedlist", connection)
SDA1.Fill(yourDataTable)
Dim bSource1 As New BindingSource
bSource1.DataSource = yourDataTable
dataGridView1.DataSource = bSource1

现在您使用 MySqlCommandBuilder自动创建 MySqlDataAdapter 的 InsertCommand、UpdateCommand 和 DeleteCommand 属性

Dim builder = new MySqlCommandBuilder(SDA1)

最后,当您准备好更新数据时,只需编写即可

Dim yourBindingSource = dataGridView1.DataSource As BindingSource
SDA1.Update(yourBindingSource.DataSource as DataTable)

网格行上不需要循环并手动构建 InsertCommand 及其参数

有关从 DbDataAdapter 派生的类应该如何工作的概述,您可以阅读 MSDN reference here

关于mysql - 如何将Datagridview中当前选定的行插入到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35184241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com