在表单加载vb.net上填充datagrid

时间:2015-10-25 15:17:48

标签: sql-server vb.net winforms datagridview

这应该是直截了当的,但它不想为我工作..

我正在尝试在表单加载时填充Datagridview。如果我使用Reloadrecords& amp;中的网格填充一个按钮,则从下面调用Populategrid(),Sub下面的工作正常。 displayrecords。

 Public Sub populategrid()
    If Trim(Me.Text) = "CIMDETAILS" Then
        da = New SqlDataAdapter("SELECT * from Interactions where [Name] like '" & txtdetect2.Text & "%' order by [IntDate] desc", SQLCon)
        dsetAssets = New DataSet
        da.Fill(dsetAssets, "Interactions")
        dgvData.DataSource = dsetAssets.Tables("Interactions").DefaultView
    Else
        ReloadRecords()
        DisplayRecords()
    End If


Public Sub DisplayRecords()
    Try
        Dim da = New SqlDataAdapter("SELECT * from Interactions order by [IntDate] desc", SQLCon)
        dsetAssets = New DataSet
        da.Fill(dsetAssets, "Interactions")
        dgvData.DataSource = dsetAssets.Tables("Interactions").DefaultView
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
    End Try

End Sub

Sub ReloadRecords()

    Try

        FillCIM("SELECT * FROM Interactions order by [IntDate] desc", dgvData)
        dgvData.Columns(0).Visible = False
        dgvData.Columns(1).Width = 300 ''Name''
        dgvData.Columns(1).HeaderCell.Value = "Customer Name"
        dgvData.Columns(2).Width = 200 ''Int type''
        dgvData.Columns(2).HeaderCell.Value = "Interaction Type"
        dgvData.Columns(3).Width = 170  ''Int Date''
        dgvData.Columns(3).HeaderCell.Value = "Interaction Date"
        dgvData.Columns(4).Width = 400   ''Remarks''
        dgvData.Columns(4).HeaderCell.Value = "Remarks"
        dgvData.Columns(5).Visible = False


    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, Me.Text)
    End Try

End Sub

 Private Sub CIMDETAILS_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ReloadRecords()
    DisplayRecords()
    Call populategrid()
End Sub

Public Function FillCIM(ByVal Sqlstring As String, ByVal MyDataGrid As DataGridView)

    Dim Constring = "Data Source=" & database & "\SQLEXPRESS; Initial Catalog = CIM; Integrated Security=true"
    Dim SQLCon As New SqlConnection(Constring)
    Dim SQLAdapter As New SqlDataAdapter()
    Dim myDataset As New DataSet()

    SQLCon.Open()

    Try
        SQLAdapter.SelectCommand = New SqlCommand(Sqlstring, SQLCon)
        SQLAdapter.Fill(myDataset)
        MyDataGrid.DataSource = myDataset.Tables(0)
    Catch ex As Exception
    End Try

    SQLCon.Close()
    SQLAdapter.Dispose()
    myDataset.Dispose()
    Return True
End Function

1 个答案:

答案 0 :(得分:0)

让这项工作非常简单。

我刚刚发现表单加载后有一个事件,显示的是表单。一旦我把populategrid()子放在那里它就可以了。