我从两个表中加载数据:机构和国家。学院有3列:instId,name,countryId。而国家有2列:countryId,countryId是国家表中的一个外键的名称。我将这两个表填入数据集中。我有datagridview并将其数据源设置为我的数据集中的表。我也创建datagridviewcomboboxcolumn并绑定它的国家表。看看下面的代码:VB.Net绑定datagridview comboboxcolumn到datagridviewTextboxColumn
Public Class frmDGV
Dim sqlConn As SqlConnection
Dim dsOptions As DataSet
Dim daInstitute As SqlDataAdapter
Dim daAdapter As SqlDataAdapter
Dim bsCountry As BindingSource
Private Sub frmTest_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Try
dsOptions = New DataSet
loadOptions()
dgvInstitute.DataSource = dsOptions.Tables("institute")
bsCountry = New BindingSource(dsOptions, "country")
Dim col As New DataGridViewComboBoxColumn
col.DataPropertyName = "countryName"
col.HeaderText = "Country"
col.Name = "cName"
col.DataSource = bsCountry
col.DisplayMember = "countryName"
col.ValueMember = "countryId"
dgvInstitute.Columns.Add(col)
dgvInstitute.Columns(0).Width = 60
dgvInstitute.Columns(1).Width = 200
dgvInstitute.Columns(2).Width = 60
dgvInstitute.Columns(3).Width = 120
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
Sub loadOptions()
Dim sql As String
Try
sqlConn = New SqlConnection(connString)
sqlConn.Open()
sql = "select instId, name, countryId from institute"
daInstitute = New SqlDataAdapter(sql, sqlConn)
daInstitute.Fill(dsOptions, "institute")
'----------------------------------------------------------------------
sql = "select countryId, countryName from country"
daAdapter = New SqlDataAdapter(sql, sqlConn)
daAdapter.Fill(dsOptions, "country")
'----------------------------------------------------------------------
sqlConn.Close()
Catch ex As Exception
sqlConn.Close()
MsgBox(Err.Description)
End Try
End Sub
End Class
我怎样才能在使用绑定技术,不使用循环DataGridView的基础上,countryId组合框显示正确的国名? 看到下面的图片:
Fabio先生,请您根据我的代码发送完整的代码吗?谢谢 –
@ HilalAl-Rajhi,我的意见是,你的代码必须工作,只改变一行,如我的答案... – Fabio
谢谢法比奥先生,你是对的。我只是修改了代码并粘贴了一行:'col.DataPropertyName =“countryId”' –