我有一個四個下拉列表,用於過濾/命令gridview。動態Linq動態錯誤Where子句
如果前3個下拉列表中的任何一個具有非0的選定值,則將WhereFlag設置爲True。第四個下拉菜單用於指定網格按哪個列排序。
我的數據綁定gridview的代碼使用System.Linq.Dynamic,如下所示...
Dim dc As New DiaryDataContext
If WhereFlag = False Then
'This section works...
Dim AList = dc.D_AreaSubAreas _
.OrderBy(ddl_SortBy.SelectedValue)
Dim dl As List(Of D_AreaSubArea)
dl = AList.ToList
dl.Insert(0, New D_AreaSubArea With {.Ref = 0,
.Area = "",
.SubArea = "",
.Allocation = "Allocation...",
.Redundant = False})
gv_AreaSubArea.DataSource = dl
gv_AreaSubArea.DataBind()
'Gridview successfully binds
'If ddl_SortBy value is changed... Gridview binds OK.
Else
'This section gives error...
Dim WhereBuild As New StringBuilder
If ddl_AreaFilter.SelectedIndex <> 0 Then
WhereBuild.Append("Area = '" & ddl_AreaFilter.SelectedValue & "'")
AndFlag = True
End If
If ddl_SubAreaFilter.SelectedIndex <> 0 Then
If AndFlag = True Then
WhereBuild.Append(" AND ")
End If
WhereBuild.Append("SubArea = '" & ddl_SubAreaFilter.SelectedValue & "'")
AndFlag = True
End If
If ddl_AllocFilter.SelectedIndex <> 0 Then
If AndFlag = True Then
WhereBuild.Append(" AND ")
End If
WhereBuild.Append("Allocation = '" & ddl_AllocFilter.SelectedValue & "'")
End If
'ERROR HERE
Dim AList = dc.D_AreaSubAreas _
.Where(WhereBuild.ToString) _
.OrderBy(ddl_SortBy.SelectedValue)
'END ERROR
Dim dl As List(Of D_AreaSubArea)
dl = AList.ToList
dl.Insert(0, New D_AreaSubArea With {.Ref = 0,
.Area = "",
.SubArea = "",
.Allocation = "Allocation...",
.Redundant = False})
gv_AreaSubArea.DataSource = dl
gv_AreaSubArea.DataBind()
End If
我得到的錯誤是與動態where子句。我得到的錯誤是
ParseException由用戶代碼未處理。字符文字必須正好包含一個字符
它指向查詢AList在Else fork中。它與If分支中查詢的唯一區別是Where子句的添加...但我一直無法推斷我的代碼出了什麼問題。 AHA。
jnovo謝謝......不幸的是,你的建議給出了一個錯誤從字符串轉換爲長類型是無效的。我試過了一個版本,其中我的WhereBuild是一個字符串構建器,另一個是我連接到的一個字符串。在VS2010中,intellisence爲最後轉義部分增加空格,使其顯示爲&「\」「) – Mych
說明所有下拉列表提供字符串值 – Mych
@Mych在您的評論後更新了答案。 – jnovo