4

您好 将所选索引的值从列表框中分配给变量的正确方法是什么?用户在列表框中选择一个项目,然后输出会根据他们的选择而变化。

我用:

variablename = listbox.text

在这种情况listBox_SelectedIndexChanged下,这有效。

当我使用我使用的button_click事件时:

variablename = listbox.selectedindex 

listbox_selectedindexchanged但这在事件中不起作用。

请让我知道是否可以像我上面那样使用它,或者我是否会遇到问题以及为什么你不能使用 selectedindex 方法。

谢谢!

4

2 回答 2

4

答:听起来您的变量是一个字符串,但您正试图将 SelectedIndex 属性返回的值分配给它,该值是一个整数。

B. 如果您试图检索与 Listbox 的 SelectedINdex 关联的项目的值,请使用索引返回 Object 本身(列表框是 Object 的列表,通常但不总是会是字符串)。

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
    'THIS retrieves the Object referenced by the SelectedIndex Property (Note that you can populate
    'the list with types other than String, so it is not a guarantee that you will get a string
    'return when using someone else's code!):
    SelectedName = ListBox1.Items(ListBox1.SelectedIndex).ToString
    MsgBox(SelectedName)
End Sub

这更直接一点,使用 SelectedItem 属性:

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged

    'This returns the SelectedItem more directly, by using the SelectedItem Property
    'in the event handler for SelectedIndexChanged:
    SelectedName = ListBox1.SelectedItem.ToString
    MsgBox(SelectedName)

End Sub
于 2011-04-03T15:07:26.060 回答
2

那么这取决于你想从列表框的选定项目中实现什么。

有几种可能的方法,让我尝试为您的家庭作业解释其中的一些方法。

假设您有一个包含两列的数据表,它们的行...

ID    Title
_________________________
1     First item's title
2     Second item's title
3     Third item's title

然后将此数据表绑定到您的列表框,

ListBox1.DisplayMember = "ID";
ListBox1.ValueMember = "Title";

如果用户从列表框中选择第二项。

现在,如果您想获取所选项目的显示值(标题),那么您可以这样做

string displayValue = ListBox1.Text;   // displayValue = Second item's title

或者甚至得到相同的结果。

// displayValue = Second item's title
string displayValue = ListBox1.SelectedItem.ToString();

并且要针对所选项目获取值成员,您需要执行

string selectedValue = ListBox1.SelectedValue;    // selectedValue = 2

现在在某些情况下,您希望允许用户从列表框中选择多个项目,因此您可以设置

ListBox1.SelectionMode = SelectionMode.MultiSimple;

或者

ListBox1.SelectionMode = SelectionMode.MultiExtended;

现在假设如果用户选择了两个项目;第二和第三。

因此,您可以通过简单地遍历SelectedItems

string displayValues = string.Empty;
foreach (object selection in ListBox1.SelectedItems)
{
    displayValues += selection.ToString() + ",";
}

// so displayValues = Second item's title, Third item's title,

如果你想得到ID's而不是Title's那样......

我也在看,如果找到我会发上来的。

我希望你的理解建立起来。

祝你好运!

于 2011-04-03T15:05:34.327 回答