gpt4 book ai didi

VB.Net 将 datagridview Comboboxcolumn 绑定(bind)到 datagridviewTextboxColumn

转载 作者:行者123 更新时间:2023-12-02 10:01:23 28 4
gpt4 key购买 nike

我正在从两个表加载数据:机构和国家。 Institute 有 3 列:instId、name、countryId。国家/地区有 2 列:国家/地区 ID、名称,其中国家/地区 ID 是国家/地区表中的外键。我将这两个表填充到数据集中。我有 datagridview 并将其数据源设置为数据集中的表。我还创建了 datagridviewcomboboxcolumn 并将其绑定(bind)到国家/地区表。看一下下面的代码:

    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

如何使用不使用循环的绑定(bind)技术根据 datagridview 中的countryId 在组合框中显示正确的国家/地区名称?见下图:enter image description here

最佳答案

更改DataPropertyName对于 datagridview 中的组合框列:

...
col.DataPropertyName = "countryId"
...

.DataPropertyName - 是 datagridview.DataSource 中的列名称,您想要在当前列中显示的内容。

关于VB.Net 将 datagridview Comboboxcolumn 绑定(bind)到 datagridviewTextboxColumn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21084106/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com