问题描述
我正在从两个表中加载数据:研究所和国家。学院有3列:instId,名称,countryId。 country具有2列:countryId,名称,其中countryId是来自国家/地区表的外键。我将这两个表填充到数据集中。我有datagridview并将其数据源设置为在我的数据集中创建表格。我还创建了datagridviewcomboboxcolumn并将其绑定到国家/地区表。看看下面的代码:
I am loading data from two tables: institute and country. Institute has 3 columns: instId, name, countryId. And country has 2 columns: countryId, name where countryId is a foreign key from country table. I fill these two tables in dataset. I have datagridview and set its datasource to institute table in my dataset. I also create datagridviewcomboboxcolumn and bind it country table. Have a look to the following code:
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在组合框中显示正确的国家名称?
请参见以下图片:
How can I display the proper country name in the combobox based on the countryId in the datagridview using the binding techniques not using a loop?See the following picture:
推荐答案
在您的datagridview中将comboboxcolumn的 DataPropertyName
更改为:
Change DataPropertyName
for comboboxcolumn in your datagridview:
...
col.DataPropertyName = "countryId"
...
.DataPropertyName
-是 datagridview.DataSource
中的列名显示在当前列中。
.DataPropertyName
- is a column name from datagridview.DataSource
,which you want to show in the current column.
这篇关于VB.Net将datagridview组合框列绑定到datagridviewTextboxColumn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!