SQL & Loading results into combobox

Trancedified
03-18-2004, 04:52 PM
Hello,

I am trying to load the results of my SQL query into a combobox called cboTemplate.

That works, but is there a way to select one of the items and do something with it?

I tried:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If cboTemplate.SelectedItem = "New" Then
MsgBox("wow")End If
End Sub

But it returns an error:

An unhandled exception of type 'System.InvalidCastException'
occurred in microsoft.visualbasic.dll

Additional information: Cast from type 'DataRowView' to
type 'String' is not valid.
'Here is my code:

Private Sub cboVolume_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cboVolume.SelectedIndexChanged

Dim strSQL As String
'Connect to the data source.
Dim objConn As SqlConnection = New SqlConnection( _
"Initial Catalog=Card Services;" & _
"Data Source=CHRISXP\LASERFICHE;Integrated Security=SSPI;")

Me.cboTemplate.Items.Clear()
Try

objConn.Open()

strSQL = "SELECT DISTINCT Tstr.TemplateName "
strSQL &= "FROM Vol, Toc, Tstr WHERE Vol.VolumeName = " & _
"'" & cboVolume.SelectedItem & "'" & _
" AND Vol.VolumeId = Toc.VolumeId AND Toc.TemplateId = Tstr.TemplateId"

Dim command As SqlCommand = New SqlCommand(strSQL, objConn)
Dim objAdapter As SqlDataAdapter = New SqlDataAdapter(command)
Dim dataSet As DataSet = New DataSet()
objAdapter.Fill(dataSet, "Tstr")

Me.cboTemplate.DataSource = dataSet.Tables("Tstr").DefaultView
Me.cboTemplate.DisplayMember = "TemplateName"

Catch ex As Exception
MsgBox(ex.Message)
Finally
objConn.Close()
End Try
End Sub



Thanks for your suggestions!

Chris

Denaes
03-19-2004, 10:36 AM
This is one of those "duh" moments. I smacked myself when I realized how easy it was.

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If cboTemplate.Text = "New" Then
MsgBox("wow")End If
End Sub

You got that exception because you were trying to compare a string to an object (items are held as objects). But even using .SelectedItem.ToString and .SelectedText didn't throw an exception, they also didn't find the match.

.Text does.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum