【问题标题】:cannot set the text of dropdown list in asp.net using vb无法使用 vb 在 asp.net 中设置下拉列表的文本
【发布时间】:2013-02-06 03:23:36
【问题描述】:

这是我填充下拉列表的代码:

For i = 1 To Convert.ToInt32(count1)
            etc.CommandText = "select Classification from schemaItemDetails.AssetCategory where ASC_ID = " & i & ""
            Dim dra1 As SqlDataReader = etc.ExecuteReader
            While (dra1.Read())
                ddonecategory.Items.Add(dra1.GetString(0))
            End While
            dra1.Close()
        Next

如何设置下拉列表的文本?因为当我使用此代码设置下拉列表的文本时:

ddonecategory.Text = "Toolings".Text

我遇到了这种错误:

'ddonecategory' has a SelectedValue which is invalid because it does not exist in the list of items.

【问题讨论】:

  • 您的代码有几个问题。你是用 WebForms 写的吗?
  • 我的代码有什么问题?
  • 首先,"Toolings".Text 不是有效代码
  • 您以这种方式填充下拉列表是否有原因?我通常会尽可能使用 DataSource,但即使您想在后面的代码中执行此操作,也不建议使用带有 SqlDataReader 的 for 循环。
  • @probackpacker - 啊是的对不起我的错误,它实际上只是“工具”。啊好的先生,我不知道数据源对不起我是新手,无论如何谢谢先生我会试试的

标签: asp.net vb.net drop-down-menu


【解决方案1】:

我不知道怎么用vb写,但是在C#中应该是这样的

   ddonecategory.SelectedIndex = 
               ddonecategory.Items.IndexOf(ddonecategory.Items.FindByText("Your value"));

关键是Items.FindByText方法
这样做的好处是,如果未找到该项目,则将其设置为 -1。
因此,如果在下拉列表中没有找到匹配项,则不会出现任何错误。

编辑-1

这里有一个很好的解释
Best way to check if a drop down list contains a value?

编辑 2

这是VB代码

 Dim searchString As String = "Toolings".Text
 If ddonecategory.Items.FindByText(searchString) IsNot Nothing Then
     Label1.Text = "Item Found: " & searchString
 Else
     Label1.Text = "Item not Found: " & searchString
 End If

【讨论】:

    猜你喜欢
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多