更新DataGridView中的问题

时间:2013-04-25 07:43:40

标签: sql vb.net datagridview

我可以使用以下SqlAdapter

来做得很好
Private SqlDA As New SqlDataAdapter("Select * from tblContacts", SqlConn)

但是,如果我在下面使用,那么在我从SQL检索数据以修改然后使用DataTable更新之后,我会因为使用率低而被抛出。顺便说一下,第一个字段有主键,即身份意味着你知道自动增加。下面不包含该字段的标题。(ContactID)

Private SqlDA As New SqlDataAdapter("Select FirstName, LastName, Email, PhoneNumber, Tarih from tblContacts", SqlConn)

以下是整个代码:

    Dim TheDataTable As New DataTable
Private SqlConn As New SqlConnection("Data Source=PC-N39\sqlexpress;Initial Catalog=ADO_PRACTICE;Persist Security Info=True;User ID=sa;Password=sas")
Private SqlDA As New SqlDataAdapter("Select * from tblContacts", SqlConn)
Private SqlDataSet As New DataSet
Private SqlCmdBuilder As New SqlCommandBuilder(SqlDA)

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
    SqlDA.Fill(TheDataTable)
    DataGridView1.DataSource = TheDataTable
    InitializeDataGridView()
End Sub

Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
    Dim x As Integer
    x = SqlDA.Update(TheDataTable)
    MessageBox.Show(CStr(x) & " record(s) updated")
End Sub

1 个答案:

答案 0 :(得分:0)

您的第二个语句不包含表的PrimaryKey或唯一索引列 这就是为什么SqlCommandBuilder无法生成适当的UPDATE / DELETE / INSERT命令查看存储在DataAdapter中的SelectCommand的原因。

除了将ContactID读入您的查询

之外,我看不到任何解决方案

See MSDN docs on SqlCommandBuilder