2013-12-21 52 views
-1

我的組合框在選擇語句中不起作用,如果我在輸入值之後聲明本身有效。我認爲組合框本身可能存在問題,或者有人可能會看到我的代碼有問題嗎?Combobox不與選擇語句一起工作

Private Sub btnViewTimeTable_Click(sender As Object, e As EventArgs) Handles btnViewTimeTable.Click 

    If (cbDay.Text = "Monday" Or cbDay.Text = "Tuesday" Or cbDay.Text = "Wednesday" Or cbDay.Text = "Thursday" Or cbDay.Text = "Friday" Or cbDay.Text = "Saturday" Or cbDay.Text = "Sunday") Then 
     Dim SqlQuery As String = "SELECT Time, Activity, Equipment FROM TimeTable WHERE Day = 'cbDay.text'" 
     Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn) 
     Dim ds As DataSet = New DataSet 
     da.Fill(ds, "Table") 
     Dim dt As DataTable = ds.Tables("Table") 

     With DGTimeTable 
      .AutoGenerateColumns = True 
      .DataSource = ds 
      .DataMember = "Table" 
     End With 

     With DGTimeTable 
      .Columns(0).Width = 108 
      .Columns(1).Width = 154 
      .Columns(2).Width = 278 
      Me.DGTimeTable.DefaultCellStyle.WrapMode = DataGridViewTriState.True 
      Me.DGTimeTable.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells 
     End With 

    Else 
     MsgBox("Please Select a Day!") 

    End If 

End Sub 

回答

0

更改這些初始行

Dim SqlQuery As String = "SELECT Time, Activity, Equipment " & _ 
         "FROM TimeTable WHERE Day = ?" 
Dim da As OleDbDataAdapter = New OleDbDataAdapter(SqlQuery, conn) 
da.SelectCommand.Parameters.AddWithValue("@p1", cbDay.text) 
Dim ds As DataSet = New DataSet 
da.Fill(ds, "Table") 
.... 

在你的原代碼,你嘗試過,單引號之間的組合和它的屬性文本的名稱,但在這種方式中的文本literraly解釋,這意味着數據庫引擎搜索記錄的列Day包含字符串值cboDay.text不是組合框的實際值

還有另一個問題。您正在使用MS-Access作爲數據庫,因此TIME和DAY是Jet-Sql中的保留關鍵字,除非將它們括在方括號中,否則無法將它們用作列名稱。如果仍有可能,我建議更改這些列的名稱,因爲每次使用此表時都會出現這個煩人的問題。

Dim SqlQuery As String = "SELECT [Time], Activity, Equipment " & _ 
         "FROM TimeTable WHERE [Day] = ?" 
+0

謝謝史蒂夫! – HaydenKThomas