我在一个面板中创建了一系列组合框,我可以用我的数据库中的正确值填充这些组合框中的每一个,但我无法提取(放入变量)我选择的值点击任何组合框。我试过几件事无济于事。我查看了某人在另一个使用列表的网站上提出的解决方案,但这不适用于我的问题,或者我不理解它。任何帮助,将不胜感激。几个星期以来,我一直在努力解决这个问题。非常感谢!
这是我的代码的相关部分:
Private Sub llenaPanelKeywords()
Try
combokywrd = New System.Windows.Forms.ComboBox
combokywrd.Left = kywrdLabel.Left + kywrdLabel.Width + 1
combokywrd.Top = 10 + SaltoDeFilaKeywords * 30
combokywrd.Width = 81
combokywrd.Height = 25
combokywrd.Font = New System.Drawing.Font("Microsoft Sans Serif", 10.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
PanelKywrds.Controls.Add(combokywrd)
combokywrd.Name = kwDataTable.Rows(kwRowPosition)("IdKeyword").ToString()
'the combo gets populated only upon clicking on it:
AddHandler combokywrd.Click, AddressOf combokywrd_click
SaltoDeFilaKeywords = SaltoDeFilaKeywords + 1
Catch ex As Exception
MessageBox.Show("falla en llenar panel keywords " & ex.Message)
End Try
End Sub
Private Sub combokywrd_click(sender As Object, e As EventArgs) Handles combokywrd.Click
Try
Dim combokywrd As ComboBox = CType(sender, ComboBox)
idKeywordSelect = combokywrd.Name.ToString()
combokywrd.DataSource = Nothing 'por alguna razón antes de poner esto, fallaba al llenar uno de los combos, pero no los demás (largo total)
combokywrd.Items.Clear()
Dim stringSQLValorKywrd = "SELECT DISTINCT valorKeyword FROM [TOOLTOWERDbase].[dbo].[articuloKeyword] WHERE idKeyword = " & idKeywordSelect
Dim cmd As New SqlCommand(stringSQLValorKywrd, con)
cmd.CommandType = CommandType.Text
Dim sda As New SqlDataAdapter(cmd)
Dim dtVK As New DataTable()
sda.Fill(dtVK)
combokywrd.DataSource = dtVK
combokywrd.DisplayMember = "valorkeyword"
lstCombos.Add(combokywrd)
combokywrd.Tag = combokywrd.Name
AddHandler (combokywrd.SelectedValueChanged), AddressOf combokywrd_SelectedValueChanged
Catch ex As Exception
MessageBox.Show("carga valoresKeyword falló " & ex.Message)
End Try
End Sub
Private Sub combokywrd_SelectedValueChanged(sender As Object, e As EventArgs) Handles combokywrd.SelectedValueChanged
'I cannot go beyond populating the comboboxes:
'I have tried with selectedindexchanged as well
MessageBox.Show(combokywrd.SelectedText.ToString()) 'shows blank
Dim cb As ComboBox = DirectCast(sender, ComboBox)
MsgBox(cb.SelectedValue.ToString()) 'shows System.Data.DataRowView
MsgBox("combobox’s tag: " & cb.Tag.ToString()) 'it shows the correct tag
Dim tempString = combokywrd.Items(combokywrd.SelectedValue).ToString 'value of ‘0’ is not valid for index
End Sub
答案 0 :(得分:0)
MsgBox(cb.SelectedValue.ToString()) 'shows System.Data.DataRowView
你得到了这个值,但你没有在组合框中放一个字符串,你在那里放了一整行。 (因为你绑定到一个表,而不是列表。)尝试cb.SelectedValue [0] .ToString(),如果这不起作用,在行上放一个断点,转到立即窗口(ctrl + g) ,键入cb.SelectedValue。并看看在第二个“。”之后出现了什么选项,你会在那里找到一些东西让你得到行的所需字段而不是整行。