1

我想insert记录从datagridviewmysql database table,但我不知道如何插入 datagridview到数据库table。怎么做?:(

4

4 回答 4

2

kumar,你的代码有问题

name = Me.DataGridView1.Rows(i).Cells(0).ToString()

  age= Me.DataGridView1.Rows(i).Cells(1).ToString()

应该

name = Me.DataGridView1.Rows(i).Cells(0).Value.ToString()

  age= Me.DataGridView1.Rows(i).Cells(1).Value.ToString()
于 2013-06-12T14:04:13.997 回答
1

这只是我的建议,如果您有代码,那么可以做得更好

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ''create connection 
        Dim conn As SqlConnection = New SqlConnection()
        conn.Open()

        Dim comm As SqlCommand = New SqlCommand()
        comm.Connection = conn

        ''insert data to sql database row by row
        Dim name, ageAs String
        For i As Integer = 0 To Me.DataGridView1.Rows.Count
            name = Me.DataGridView1.Rows(i).Cells(0).ToString()
            age= Me.DataGridView1.Rows(i).Cells(1).ToString()

            comm.CommandText = "insert into mytable(name,age) values('" & name & "','" & age& "')"
            comm.ExecuteNonQuery()
        Next

        conn.Close()

    End Sub

这只是一种插入方式,最好使用存储过程插入值,因为如果使用 SQL,可能会发生 SQL 注入。所以存储过程是最好的保存方式。

于 2013-04-16T08:08:57.207 回答
0

而不是插入数据,我试图更新记录,对我来说

Me.AddPurchases.Rows(i).Cells(0).Value.ToString()

此语句没有解决目的此语句将返回行数和列数,如 { row=0,col=1} 下一次迭代 { row=0,col=1} 等等,但是

Dim roid As String

    For i As Integer = 0 To Me.edit_role_grid.RowCount - 1
        roid = Me.edit_role_grid.Rows(i).Cells(0).FormattedValue
        MsgBox(roid) 

这对我来说很好,这是返回单元格的文本,现在这个值可以在任何地方使用

于 2013-09-04T00:42:36.707 回答
0

更改代码行:

 For i As Integer = 0 To Me.AddPurchases.Rows.Count

用这条线:

 For i As Integer = 0 To Me.AddPurchases.Rows.Count - 1 

以上是verohwm消息异常的解决方法。*

于 2013-08-23T10:49:13.973 回答