我有一个datagridview(带有bindingsource,一个来自master的细节),它是通过数据读取器以编程方式填充的。Datareader成功检索所有数据并将新行添加到bindingsource。然而,datagridview仅显示一行。因此,在datagridview中,它显示的是数据读取器的最后一行。
当我从(主控件的)bindingnavigator中单击“上一步”按钮时,所有行都显示在datagridview中,就好像它正在刷新bindingsource并将每一行绑定到每个datagridview行。我知道我错过了一些东西,但不知道是什么。
Private Sub PopulateDetails(ByVal orderno As String)
Dim cmd As New SqlClient.SqlCommand
Dim dr As SqlClient.SqlDataReader
LoadDB()
If Not con.State = ConnectionState.Open Then
con.Open()
End If
cmd.CommandText = "select orderid, pono, cono, styleno, fabriccodeid, custfabriccode, colorid, orderqty, totalbales, uomid, width, " &
"weightperarea, yard, gramperyard, size, unitprice, currencycode, deliverydt, remark from tblorderdetails " &
"where orderno = @orderno;"
cmd.Connection = con
cmd.Prepare()
cmd.Parameters.AddWithValue("@orderno", orderno)
dr = cmd.ExecuteReader
With dr
If .HasRows() Then
Dim newRow As DataRowView
While .Read
newRow = DirectCast(TblorderdetailsBindingSource.AddNew(), DataRowView)
newRow.BeginEdit()
newRow.Row.BeginEdit()
newRow.Row("orderno") = OrdernoTextBox.Text
newRow.Row("pono") = .Item("pono")
newRow.Row("cono") = .Item("cono")
newRow.Row("styleno") = .Item("styleno")
newRow.Row("fabriccodeid") = .Item("fabriccodeid")
newRow.Row("custfabriccode") = .Item("custfabriccode")
''newRow("btncolor") = .Item("colorid")
newRow.Row("orderqty") = .Item("orderqty")
newRow.Row("totalbales") = .Item("totalbales")
newRow.Row("uomid") = .Item("uomid")
newRow.Row("width") = .Item("width")
newRow.Row("weightperarea") = .Item("weightperarea")
newRow.Row("yard") = .Item("yard")
newRow.Row("gramperyard") = .Item("gramperyard")
newRow.Row("size") = .Item("size")
newRow.Row("unitprice") = .Item("unitprice")
newRow.Row("currencycode") = .Item("currencycode")
newRow.Row("deliverydt") = .Item("deliverydt")
newRow.Row("remark") = .Item("remark")
newRow.Row.EndEdit()
newRow.DataView.Table.Rows.Add(newRow.Row)
End While
End If
.Close()
End With
con.Close()
End Sub
这是非常错误的错误方法。调用ExecteReader
后,只需调用DataTable
的Load
方法并传递数据读取器。这将添加所有行甚至列,如果它们还不存在。或者,使用数据适配器并调用其Fill
方法,将DataTable
作为参数传递。结果相同。
我已经工作了4天,想办法在datagridview中显示所有行,最后通过以下方式解决:
TblorderBindingSource.MovePrevious()
TblorderBindingSource.MoveNext()
显然,bindingnavigator需要以某种方式刷新bindingsource,然后它只显示datagridview中添加的所有行(自动生成的列id为-1、-2、-3…)。用户可以修改这些行,然后保存。
我很遗憾,这似乎不是一个“智能”的变通方法,但很高兴它以某种方式起作用。