VB.NET-一种将行插入datagrid或datatable的方法

时间:2013-07-30 17:26:23

标签: vb.net datagrid datatable richtextbox

嗨再次被困在中间我需要一些指针......我需要一种方法在for循环中填充datagrid ...

Dim rs As SqlCommand
Dim dt As New DataTable
For Each line As String In RichTextBox1.Lines
query = "myquery '" & RichTextBox1.Lines(i).ToString & "'"
rs = New SqlCommand(query, Module1.dtsrv_conn)
dt.load(rs.Executereader)
        If i < 1 Then
            DataGridView1.DataSource = dt                
        Else
            datagridview1.rows.Add(rs.ExecuteReader)
        End If
        i = i + 1
    Next

将在RichTextBox中输入多行文本,并且每行需要与数据库中的值进行比较,结果表需要在datagrid中显示...我尝试将新查询的行直接添加到datagrid,但它会抛出异常所以我试图将新行添加到datatable并稍后加载datagrid但我找不到方法....

1 个答案:

答案 0 :(得分:0)

如果我理解您的问题不是很清楚,则用户输入要查询数据库中行的值,如果存在,则显示一些相应的数据或消息。

听起来你要做的就是将datagrid绑定到数据源,在我的示例中是一个内存数据表,然后通过DataGridView1.CellFormatting拦截数据绑定,以相应地比较/修改数据。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Dim sqlConnection As SqlConnection
    Dim sqlConnectionString As String = "YourConnectionString"
    Dim sqlDataAdapter As SqlDataAdapter
    Dim dataTable As New DataTable
    Dim sqlCommand As SqlCommand
    Dim sqlString As String
    Try
        sqlString = "SELECT * FROM YourTable" 'if user input values are filters, loop through and append them in WHERE clause
        sqlConnection = New SqlConnection(sqlConnectionString)
        sqlCommand = New SqlCommand(sqlString, sqlConnection)
        sqlConnection.Open()
        sqlDataAdapter = New SqlDataAdapter(sqlCommand)
        sqlDataAdapter.Fill(dataTable)
        sqlConnection.Close()

        DataGridView1.DataSource = dataTable

    Catch ex As Exception
        'Handle error
    End Try

End Sub

Private Sub DataGridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles DataGridView1.CellFormatting

    If Me.DataGridView1.Columns(e.ColumnIndex).Name = "YourColumnNameToCompare" Then
        If e.Value IsNot Nothing Then
            'do your comparison to user input text here and if necassary change the value like so..
            For Each line In RichTextBox1.Lines
                If line = e.Value Then
                    e.Value = "Value modified"
                    Exit For
                End If
            Next

            e.FormattingApplied = True
        End If
    End If
End Sub