从sql表填充数据网格视图

时间:2013-01-21 10:31:40

标签: vb.net sql-server-2005 datagridview

我在Datagridview中有四列。我想用sql数据库中的数据填充前两列。我尝试填写Datagridview。它不显示数据,但会生成行。

这是我的代码:

getConnect()
    Try
        Conn.Open()
        Dim strSQL As String = "SELECT EMP_ID, EMP_NAME FROM EMPLOYEE ORDER BY EMP_NAME ASC"
        Conn.Close()
        Dim da As New SqlDataAdapter(strSQL, Conn)
        Dim dt As New DataTable("EMPLOYEE")
        da.Fill(dt)
        ATCGRID.DataSource = dt
    Catch ex As SqlException
        MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
    Catch ex As Exception
        MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
    End Try

请检查我的代码并给我解决方案......

3 个答案:

答案 0 :(得分:2)

试试这段代码。

getConnect()
Try
    Conn.Open()
    Dim strSQL As String = "SELECT EMP_ID, EMP_NAME FROM EMPLOYEE ORDER BY EMP_NAME ASC"
    Conn.Close()
    Dim da As New SqlDataAdapter(strSQL, Conn)
    Dim ds As new Dataset
    da.Fill(ds,"EMPLOYEE")
    ATCGRID.DataSource = ds.tables(0)
Catch ex As SqlException
    MsgBox(ex.Message, MsgBoxStyle.Critical, "SQL Error")
Catch ex As Exception
    MsgBox(ex.Message, MsgBoxStyle.Critical, "General Error")
End Try

答案 1 :(得分:0)

感谢sub getConnect()它完美无缺。我也工作了。

Sub RefreshGrid()
 ' refresh the datagrid
  OpenConnect()

CmdSql.CommandText = "SELECT manager_id,manager_name FROM   tbl_Manager"
    Dim ds As DataSet = New DataSet()
    adp.Fill(ds)
    dgvMgr.DataSource = ds.Tables(0)
    'THIS MODULE WORKED JUST Please Fill Property Columns 
    'DataPropertyName as Field Database, 
    'Eg : Column1-DataPropertyName=manager_id and so on.
End Sub

答案 2 :(得分:0)

Public Sub OpenConnect()

    Try
        CmdSql.Connection = conn
        conn.Open()
        CmdSql.CommandType = CommandType.Text

    Catch ex As Exception
        ' MsgBox(ex.Message)
    End Try
End Sub

'这完美地运作了