vb.net 从sql表填充数据网格视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14436710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:36:06  来源:igfitidea点击:

Fill data grid view from sql table

vb.netsql-server-2005datagridview

提问by Thanzeem

I have four columns in Datagridview. I want to fill first two columns with data from sql database. I try to fill Datagridview. It not display data, but it generate rows.

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

This is my code:

这是我的代码:

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

Please check my code and give me solution...

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

回答by saysansay

Try this code .

试试这个代码。

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

回答by Karl Azoms

Thanks for the sub getConnect()it worked perfectly. mine also worked.

感谢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

回答by Karl Azoms

Public Sub OpenConnect()

公共子 OpenConnect()

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

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

' this worked perfectly

'这完美地工作