我從兩個表中加載數據:機構和國家。學院有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」' –