2013-10-18 65 views
1

我在MS Access中創建了一個數據庫,並將其移植到VB.NET中。DataGridViewComboBoxColumn所選值

我正在做大部分代碼工作。

我有一個連續的子表單,其中包含一個組合框填充表(tblSubject)的值。它有一個關鍵列和一個值列。

tblSubject SubjectID(PK)|標題

它使用鏈接主/子字段鏈接到父窗體。

這被用於填充在tblChoice的SubjectID,

tblChoice ChoiceID(PK)| StudentID(FK)| SubjectID(FK)|筆記

我決定使用DataGridView來顯示這些數據。

從我的研究中,我已經將DataGridViewComboBoxColumn添加到DataGridView。

我希望能夠將組合框設置爲tblChoice中的值,但我正在努力解決問題。 我錯過了一些明顯的東西嗎?


我找到了一種方法來設置值到一個特定的行,但我需要這是從表中的值,因爲每個可能是不同的。

For Each dgvRow As DataGridViewRow In dgvChoices.Rows 
    dgvRow.Cells(SubjectComboBoxColumn.Name).Value = 3 'dgvChoices.Rows.Item 
Next 

http://vbcity.com/forums/t/165967.aspx


我需要尋找到的DataGridViewComboBoxCell

'Dim dgvcbc As DataGridViewComboBoxCell = DirectCast(dgvChoices.Rows(0).Cells(0), DataGridViewComboBoxCell) 


代碼

Dim dbProvider As String 
Dim dbSource As String 
Dim conStudent As New OleDb.OleDbConnection 

'Choices 
Dim dsChoices As New DataSet 
Dim daChoices As OleDb.OleDbDataAdapter 
Dim dvChoices As New DataView 
Dim sqlChoices As String 

'Subjects 
Dim dsSubjects As New DataSet 
Dim daSubjects As OleDb.OleDbDataAdapter 
Dim sqlSubjects As String 

Private Sub frmNAME_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
    'dbProvider = "PROVIDER=Microsoft.Jet.OLEDB.4.0;" '.mdb 
    dbProvider = "Provider=Microsoft.ACE.OLEDB.12.0;" '.accdb 
    dbSource = "Data Source=C:\db.accdb" 
    conStudent.ConnectionString = dbProvider & dbSource 
    conStudent.Open() 

    sqlChoices = "SELECT * FROM tblChoice WHERE StudentID=" & txtStudentID.Text 
    daChoices = New OleDb.OleDbDataAdapter(sqlChoices, conStudent) 
    daChoices.Fill(dsChoices, "Choices") 
    'Populate the DataGridView 
    dvChoices = dsChoices.Tables("Choices").DefaultView 
    'dgvNotes.DataSource = dsChoices.Tables("Choices") 
    dgvChoices.DataSource = dvChoices 

    'Subjects Combo 
    sqlSubjects = "SELECT * FROM tblSubject" 
    daSubjects = New OleDb.OleDbDataAdapter(sqlSubjects, conStudent) 
    daSubjects.Fill(dsSubjects, "Subjects") 

    Dim SubjectComboBoxColumn As New DataGridViewComboBoxColumn 
    With SubjectComboBoxColumn 
     .DataSource = dsSubjects.Tables("Subjects").DefaultView 
     .DisplayMember = "Subject" 
     .ValueMember = "SubjectID" 
     '.DisplayIndex = 0 
    End With 
    dgvChoices.Columns.Add(SubjectComboBoxColumn) 

    conStudent.Close() 
End Sub 


其它鏈接

我並不需要一個默認值,但發現這是有用的。

col.DefaultCellStyle.DataSourceNullValue = 1; //this is not index! It is value binded to 'ValueMember' 

selecting value from DataGridViewComboBoxColumn?

回答

1

應設置組合框DisplayMember和ValueMember在您的組合框你想要的字段,然後設置DataPropertyName您要在子錶鏈接領域。

你有大部分,因爲你正在做的SELECT *,我不知道你的字段名,但假設它在「tblChoice」錶鏈接到「SubjectID」,你會想:

.DataPropertyName = "SubjectID" 
+0

這的確是鏈接到SubjectID。 謝謝:) –

相關問題