【问题标题】:Code a button to open form, based on what is selected in list box (list box selected index is from a SQL Server)根据列表框中选择的内容编写一个打开表单的按钮(列表框选择的索引来自 SQL Server)
【发布时间】:2013-10-13 17:44:27
【问题描述】:

我正在构建一个包含购物等物品的应用程序,用户(在登录并选择“浏览类别”后)然后可以看到一个列表框和按钮(以及一个返回按钮)。列表框具有类别名称,并且对于每个类别,都有一个表格保存该类别下项目的数据。该列表框具有到 SQL Server 的数据绑定,其中选定的索引是表“tblNamesOfCats”。它下方的按钮显示“选择类别”。用户应该选择一个类别,然后单击按钮以查看该类别的表单。但是,我尝试了以下代码 -

Private Sub btnSelectCat_Click(sender As Object, e As EventArgs) Handles btnSelectCat.Click

    If lbxCatList.SelectedItem = ("Action Figures") Then
        frmCatsActionFigures.Show()
    End If

End Sub

Note-btnSelectCat 是按钮,lbxCatList 是列表框,frmCatsActionFigures 是 Action Figures 类别的表单。

但是,当我尝试调试它时,我最终得到了这个错误 -

Overload resolution failed because no Public '=' can be called with these arguments:

'Public Shared Operator =(a As String, b As String) As Boolean':

    Argument matching parameter 'a' cannot convert from 'DataRowView' to 'String'.

我应该使用什么代码?我该如何解决这个问题?

更新(1)- 如前所述,列表框由一个 SQL Server 表填充,该表只有一列,称为“类别名称”,并且行中只包含每个类别的名称。 这是一些错误的截图(显然你必须点击链接,因为我没有足够高的声誉来发布图片)-

https://sites.google.com/a/devincave.com/temporaryimagesite/

【问题讨论】:

    标签: sql sql-server vb.net listbox


    【解决方案1】:
    Private Sub btnSelectCat_Click(sender As Object, e As EventArgs) Handles btnSelectCat.Click
    
        If lbxCatList.SelectedItem.ToString() = "Action Figures" Then
            frmCatsActionFigures.Show()
        End If
    
    End Sub
    

    【讨论】:

    • 当我尝试这个时,什么也没有发生
    • 如果您调试 lbxCatList.SelectedItem.ToString() 以查看单击按钮时的实际值是什么。
    • 恐怕我不明白你的意思。你能解释更多吗?我确实尝试调试到当我单击按钮时,会出现一个消息框,显示列表框的选定项,其中包含以下代码 - MessageBox.Show(lbxCatList.SelectedItem.ToString) 但是,当我调试时,这是显示在消息框-“System.Data.DataRowView”
    • 尝试 lbxCatList.Items(lbxCatList.SelectedIndex).ToString
    • 我尝试了该代码,但没有任何反应(再次)。所以,我再次使用消息框来查看会显示什么。同样,它是 System.Data.DataRowView
    【解决方案2】:

    当您将数据库表绑定到列表框时,数据行视图(数据源)中的行将存储在列表框中,而不是这些行中的列中的数据。所以它不是文本。但 DRV 对象。在错误信息中:

    Argument matching parameter 'a' cannot convert from 'DataRowView' to 'String'
    

    “Action Figures”是'String'部分,SelectedItem是DRV对象行,所以必须这样对待。

      ' works for ONE col views or when the column you want is #0 
      ' else use the right index
       If lbxCatList.SelectedItem.Item(0).ToString = "Action Figures" Then
    

    或

       If lbxCatList.SelectedItem.Item("Category").ToString = "Action Figures" Then
    

    或将其转换回 drv 行(上面基本上是这个的简写):

       Dim drv As DataRowView = lbxCatList.SelectedItem
    
       If drv.Item("Category").ToString                  ' or use index of 0
    

    使用后一个版本,您可以在此处设置中断并将鼠标悬停在 drv 上,以查看所有属性和值,从而弄清楚您想要的位置以及如何获取它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      相关资源
      最近更新 更多