我正在使用vb 10和ms访问数据库。我有一个DataGridView
,其中包含两列("Address", "City")
。每次我从每列保存两行到我的数据库表。我总是检索总共6行,每行2列。 db的第1行和第2行与dgview的第1行相同,db的第3行和第4行与dgview
的第2行相同,而dbase的第5行和第6行为空白。
我不知道如何使我的For语句正确。我研究了很多链接,但我没有找到任何密切的答案。很抱歉给您带来不便,希望您帮助我们。谢谢!
我的代码(在cmdSave_Click
下):
Sub DataGridViewDetails()
Dim Address, City As String
For i As Integer = 0 To Me.DataGridView.RowCount - 1
Address = Me.DataGridView.Item(0, i).Value
City = Me.DataGridView.Item(1, i).Value
sql = "insert into Address(Address1 ,City) values('" & Address & "','" & City & "')"
Dim comm As New OleDb.OleDbCommand
comm.CommandText = sql
comm.Connection = con2
con2.Open()
comm.ExecuteNonQuery()
da.SelectCommand = comm
dr = comm.ExecuteReader
comm.Dispose()
MsgBox("Address Details Added!", MsgBoxStyle.Information, "Add")
con2.Close()
Next
End Sub
答案 0 :(得分:0)
这两行代码的目的是什么?对我来说,看起来它再次执行相同的插入命令? (因此重复)
public JsonResult Subgrid(String id)
{
Database1Entities db = new Database1Entities();
Product p= new Product {No=1,Item="Juice",Quantity=23};
var jsondata = new { rows=2,
cell = new string[] { p.No.ToString(),
p.Item,p.Quantity.ToString()}.ToArray()
};
return Json(jsondata, JsonRequestBehavior.AllowGet);
}
对于空行,DataGridView底部会有一个空行以允许添加更多数据,请尝试将for循环更改为此
da.SelectCommand = comm
dr = comm.ExecuteReader
答案 1 :(得分:0)
对代码进行以下更改:
Sub DataGridViewDetails()
Dim Address, City As String
For i As Integer = 0 To Me.DataGridView.RowCount - 2
Address = Me.DataGridView.Item(0, i).Value
City = Me.DataGridView.Item(1, i).Value
sql = "insert into Address(Address1 ,City) values('" & Address & "','" & City & "')"
Dim comm As New OleDb.OleDbCommand
comm.CommandText = sql
comm.Connection = con2
con2.Open()
comm.ExecuteNonQuery()
da.SelectCommand = comm
'dr = comm.ExecuteReader
comm.Dispose()
MsgBox("Address Details Added!", MsgBoxStyle.Information, "Add")
con2.Close()
Next
End Sub
答案 2 :(得分:0)
首先,我们必须添加以下声明:
Imports System.Data.OleDb
Public Class Form1
'Change "C:\Users\Jimmy\Documents\Merchandise.accdb" to your database location
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Jimmy\Documents\Merchandise.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
显示按钮代码
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select * from [items]", MyConn) 'Change items to your database name
da.Fill(ds, "items") 'Change items to your database name
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
End Sub