VB.net 从 Mysql 加载数据到 datagridview
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29674043/
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
VB.net Loading data to datagridview from Mysql
提问by Lee Song
I have a datagridview and I already put 3 columns in there (via design), but when I run this code, it adds another 3 columns and the data loads in those newly created ones. How can it just load the data from the columns that I made?
我有一个 datagridview 并且我已经在其中放置了 3 列(通过设计),但是当我运行此代码时,它又添加了 3 列并且数据加载到那些新创建的列中。它怎么能从我制作的列中加载数据?
EDIT: 1st and 2nd Column is textbox, and 3rd is combobox.
编辑:第一列和第二列是文本框,第三列是组合框。
the code is in form load:
代码在表单加载中:
Dim sqlDataAdapter As New MySqlDataAdapter
Dim dt As New DataTable
Dim bSource As New BindingSource
Try
sqlconn.Open()
Dim query As String
query = "SELECT * FROM tbl_subject ORDER BY yearlevel, code"
sqlcommand = New MySqlCommand(query, sqlconn)
sqlDataAdapter.SelectCommand = sqlcommand
sqlDataAdapter.Fill(dt)
bSource.DataSource = dt
datagrid_Subject.DataSource = bSource
sqlDataAdapter.Update(dt)
sqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
sqlconn.Dispose()
End Try
回答by Fabio
Columns of DataGridViewhave property DataPropertyName, set it value to column names from your sql query.
This will show data in predefined columns
DataGridView具有属性的列DataPropertyName,将其值设置为 sql 查询中的列名。
这将在预定义的列中显示数据
And as @Icepickle said in the comments set datagrid_Subject.AutoGenerateColumns = False
This will prevent datagridview to generate columns for all fields used in the SELECTstatements of your sql query
正如@Icepickle 在评论集中所说,datagrid_Subject.AutoGenerateColumns = False
这将阻止 datagridview 为SELECTsql 查询语句中使用的所有字段生成列
回答by W.Hillary
just go to toolbox and drag and drop datagridview, on properties name it something like dgvSubject example using your code above it will look like this;
只需转到工具箱并拖放 datagridview,在属性上将其命名为 dgvSubject 示例,使用上面的代码,它看起来像这样;
Dim sqlDataAdapter As New MySqlDataAdapter Dim dt As New DataTable Dim bSource As New BindingSource
将 sqlDataAdapter 调暗为新的 MySqlDataAdapter 将 dt 调暗为新的 DataTable 将 bSource 调暗为新的 BindingSource
Try
sqlconn.Open()
Dim query As String
query = "SELECT * FROM tbl_subject ORDER BY yearlevel, code"
sqlcommand = New MySqlCommand(query, sqlconn)
sqlDataAdapter.SelectCommand = sqlcommand
sqlDataAdapter.Fill(dt)
bSource.DataSource = dt
dgvSubject.DataSource = bSource
sqlDataAdapter.Update(dt)
sqlconn.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
sqlconn.Dispose()
End Try

