如何使用DataGridView更新数据库

时间:2016-07-13 19:59:14

标签: vb.net datagridview

基本上我有一个datagridview,在加载页面时由查询填充,以显示我的数据库表中的所有未完成订单,如下所示:enter image description here

我想知道是否可以允许用户编辑它们以便他们可以将不完整的订单标记为已完成,我正在考虑通过仅允许列可编辑,或者可能是每行旁边的一组复选框将它们标记为已完成。

这是我当前的代码页面:

Public Class processorders
    Dim sql As New sqlcontrol

    Private Sub ammendorders_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        If sql.HasConnection = True Then
            sql.RunQuery("SELECT customers.customer_id, first_name, second_name, phone_number, date_ordered, order_total, collection_method FROM (Orders INNER JOIN Customers on orders.customer_id = customers.customer_id) WHERE order_status='In Progress'")
            If sql.sqldataset.Tables.Count > 0 Then
                dgvData.DataSource = sql.sqldataset.Tables(0)
            End If
        End If

    End Sub
    'above queries database to find all incomplete orders



    Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
        Me.Close()
    End Sub

2 个答案:

答案 0 :(得分:0)

如果要编辑order_status字段,可以将该列设置为DataGridViewComboBox,其中包含所有可能的状态值。然后创建一个事件处理程序,以在更改组合框值时更新数据库。

编辑:代码

Private Sub MyDataGridView_RowValidated(sender As Object, e As DataGridViewCellEventArgs) Handles MyDataGridView.RowValidated

  'update the data source here, could vary depending on the method used.
  if sql.HasConnection
    Dim sqlCmd as SqlCommand = new SqlCommand

    sqlCmd.connection = "<Your connection string>"
    sqlCmd.commandText = 
      String.format(
        "UPDATE Orders SET order_status='{0}' WHERE customer_id='{2}';",
        MyDataGridView.Rows(e.RowIndex).Cells(<order_status column index>).Value,
        MyDataGridView.Rows(e.RowIndex).Cells(<customer_id column index>).Value
      )
    sqlCmd.ExecuteNonQuery
  end if
End Sub

编辑1:找到另一个可能的答案:DataGridView Cell Editing and Updating DB (C#)

编辑2:将sql.RunQuery更改为SqlCommand对象。

答案 1 :(得分:0)

我就是这样做的。这被挂钩到下拉列表,但它可以挂钩到网格中的任何控件:

' This enables you to capture the Update event on a gridview

Dim clickedRow As GridViewRow = TryCast(DirectCast(sender, DropDownList).NamingContainer, GridViewRow)


Dim cust_id As Label = DirectCast(clickedRow.FindControl("lbl_grd_id"), Label)
Dim status As DropDownList = DirectCast(clickedRow.FindControl("ddl_grd_crew_id"), DropDownList)


Dim cmd As New SqlCommand()
cmd.CommandText = "UPDATE [your_orders_table] set status = @status where customer_id = @cust_id "

cmd.Parameters.Add("@cust_id", SqlDbType.Int).Value = Convert.ToInt32(cust_id.Text)
cmd.Parameters.Add("@status", SqlDbType.VarChar).Value = status.Text

cmd.CommandType = CommandType.Text
cmd.Connection = Me.sqlConnection1
Me.sqlConnection1.Open()
'execute insert statement
cmd.ExecuteNonQuery()
Me.sqlConnection1.Close()
're-populate grid with a method call. if you don't the edits will not be reflected when the grid reloads 
fill_order_status_grd()

fill_order_status_grd.databind()