[英]How to Fill Data From Database to datagridview and combobox - vb.net
我需要將數據庫中的數據填充到我的Datagrid和兩個Combobox中。
我有3張桌子,“ Tipo”,“ Marca”和“ Modelo”。 表“ Modelo”具有來自“ Tipo”和“ Marca”的兩個外鍵。
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CarregarDados()
End Sub
Private Sub CarregarDados()
cn.ConnectionString = "server=localhost;user id=root;database=automoveldb"
cn.Open()
'Load DataGridView
Try
With Cmd
.CommandType = CommandType.Text
.CommandText = "SELECT modelo.id Id, marca.Nome NomeMarca, tipo.Nome NomeTipo, modelo.Nome NomeModelo FROM modelo INNER JOIN Marca ON marca.id = modelo.IdMarca JOIN tipo ON tipo.id = modelo.IdTipo;"
.Connection = cn
End With
MsgBox(Cmd.CommandText)
With Da
.SelectCommand = Cmd
.Fill(dt)
dgvModelo.DataSource = dt
End With
Catch ex As Exception
MsgBox(ex.Message)
Finally
cn.Close()
End Try
'*************************
Try
With Cmd
.CommandType = CommandType.Text
.CommandText = "SELECT * FROM Tipo;"
.Connection = cn
End With
MsgBox(Cmd.CommandText)
With Da
.SelectCommand = Cmd
.Fill(dt)
cmbTipo.ValueMember = "Id"
cmbTipo.DisplayMember = "Nome"
cmbTipo.DataSource = dt
End With
Catch ex As Exception
MsgBox(ex.Message)
Finally
cn.Close()
End Try
End Sub
MyDatabase的
結果我的代碼
我的組合框類型已填充,但在datagridview中添加了新列,我不想要它
我找到了解決該問題的解決方案,因此,如果有人想在同一功能中填充數據網格和組合框,請執行以下操作:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CarregarDados()
End Sub
Private Sub CarregarDados()
cn.ConnectionString = "server=localhost;user id=root;database=automoveldb"
cn.Open()
'***********************Load DataGridView
Try
With Cmd
.CommandType = CommandType.Text
.CommandText = "SELECT modelo.id Id, marca.Nome NomeMarca, tipo.Nome NomeTipo, modelo.Nome NomeModelo FROM modelo INNER JOIN Marca ON marca.id = modelo.IdMarca JOIN tipo ON tipo.id = modelo.IdTipo;"
.Connection = cn
End With
With Da
.SelectCommand = Cmd
.Fill(dt)
dgvModelo.DataSource = dt
End With
Catch ex As Exception
MsgBox(ex.Message)
Finally
cn.Close()
End Try
'************************* Load ComboBox Tipo
Try
With Cmd
.CommandType = CommandType.Text
.CommandText = "SELECT * FROM Tipo;"
.Connection = cn
End With
With Da
.SelectCommand = Cmd
.Fill(ds, "tipo")
End With
cmbTipo.ValueMember = "Id"
cmbTipo.DisplayMember = "Nome"
cmbTipo.DataSource = ds.Tables("tipo")
Catch ex As Exception
MsgBox(ex.Message)
Finally
cn.Close()
End Try
'************************* Load ComboBox Marca
Try
With Cmd
.CommandType = CommandType.Text
.CommandText = "SELECT * FROM Marca;"
.Connection = cn
End With
With Da
.SelectCommand = Cmd
.Fill(ds, "marca")
End With
cmbMarca.ValueMember = "Id"
cmbMarca.DisplayMember = "Nome"
cmbMarca.DataSource = ds.Tables("marca")
Catch ex As Exception
MsgBox(ex.Message)
Finally
cn.Close()
End Try
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.